首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Nginx根据其他服务的响应进行转发

Nginx根据其他服务的响应进行转发
EN

Stack Overflow用户
提问于 2019-09-02 12:30:31
回答 1查看 350关注 0票数 0

我有一个nginx设置,用于反向代理到我的后端服务器。我有一个要求,我需要发送流量到一个IP,如果它是从另一个HTTP请求成功检索,否则发送到另一个IP。比如我有一个带有request_param=abcd的传入请求(它可以是任何值)。如果我能够从http://service/abcd中检索到,则将其路由到IP1,否则将其路由到IP2。

如下所示:

代码语言:javascript
运行
复制
server {
     location /${abcd} {
     if(http://service/$abcd returns HTTP 200)
          then proxy_pass http://$http_host_1$request_uri;
     else
         proxy_pass http://$http_host_2$request_uri;
     ...
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-30 08:48:43

Openresty就是这个问题的解决方案-它构建在nginx之上,让我们配置lua代码来拦截nginx请求处理,并放入我们的自定义代码。https://openresty-reference.readthedocs.io/en/latest/Directives/

我在访问阶段使用rewrite_by_lua根据条件重定向请求。

还需要使用库lua-resty-http来发出外部请求。

cd /usr/local/openresty/lualib/resty curl -O https://raw.githubusercontent.com/ledgetech/lua-resty-http/v0.15/lib/resty/http.lua curl -O https://raw.githubusercontent.com/ledgetech/lua-resty-http/v0.15/lib/resty/http_headers.lua

代码语言:javascript
运行
复制
server {
    listen 443;

    location /location {
        lua_need_request_body on;
        set $backendurl 'http_host_1/request_uri';

        rewrite_by_lua_block {
            local body = ngx.req.get_body_data()
            local abcd = ""

            if (body) then
                abcd = string.match(body, "my_pattern")

                if (abcd ~= nil and abcd ~= '') then
                   local http = require "resty.http"
                   local httpc = http.new()
                   local external_url = "http://service/" .. abcd
                   local res, err = httpc:request_uri(external_url, {
                            method = "GET",
                            headers = {
                            ["Content-Type"] = "application/json"
                            }
                        })

                        local response_status = res.status

                        if response_status == 404 then
                            ngx.var.backendurl = "http_host_2"
                        end
                 end
            end
        }

        proxy_pass http://$backendurl/$uri;
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57751444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档