NGINX基于if-else条件的proxy_pass

问题陈述

我想根据请求头中存在的某个值将 proxy_pass 到另一个 URL,包括请求中所有的细节,包括查询参数(如果有),标头和所有内容都应传递到代理地址。

我尝试过的

我遵循了 SO post 中提到的要求,按照需求我试了一下以下内容。

Test.lua file

local token = ngx.var.http_Authorization
if token == "hello"
then
-- ngx.print ("hello")
local res = ngx.location.capture("/someURL")
if res.status == 200
then ngx.print(res.body)
end
end

nginx.conf

location /api/employees {
        content_by_lua_file test.lua;
}
location /someURL {
    internal;
    proxy_pass http://productionURL?q1=123&name=xyz;
    #proxy_redirect default;
}

如您所见,我正在在 proxy_pass 语句中手动传递查询参数。

如何通过不传递实际 request 解决此问题?

点赞
用户1058509
用户1058509

你可以通过根据头来重新编写原始请求来轻松解决这个问题。 下面是一个例子:

#样例后端
set $backend_host "http://httpbin.org";

location ~*/api/employees {
        rewrite_by_lua '
             --读取请求头
             local req_headers = ngx.req.get_headers()
             local target_uri  = ""
             -- 检查头值以确定目标URI
             if req_headers["x-special-header"] then
                target_uri = req_headers["x-special-header"]
             else
                -- 如果未找到头,则使用默认路径
                target_uri = "/get"
             end
            ngx.log(ngx.NOTICE, string.format("resolved target_uri: %s", target_uri))
            --根据头重写URI(所有原始请求参数和头都将被保留)
            ngx.req.set_uri(target_uri)
        ';
        proxy_pass $backend_host;
}

发送包含 'special' header 作为目标后端路径的样例请求:

curl 'http://localhost/api/employees?arg1=val1&arg2=val2' -H 'x-special-header: /headers'

响应:

    {
  "headers": {
    "Accept": "*/*",
    "Connect-Time": "0",
    "Connection": "close",
    "Host": "httpbin.org",
    "Total-Route-Time": "0",
    "User-Agent": "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2",
    "Via": "1.1 vegur",
    "X-Request-Id": "6e515e0a-0061-4576-b1aa-5da3e3308c81",
    "X-Special-Header": "/headers"
  }

不包含 'special' header 的样例请求:

curl 'http://localhost/api/employees?arg1=val1&arg2=val2'

响应:

{
  "args": {
    "arg1": "val1",
    "arg2": "val2"
  },
  "headers": {
    "Accept": "*/*",
    "Connect-Time": "4",
    "Connection": "close",
    "Host": "httpbin.org",
    "Total-Route-Time": "0",
    "User-Agent": "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2",
    "Via": "1.1 vegur",
    "X-Request-Id": "520c0e12-1361-4c78-8bdf-1bff3f9d924c"
  },
  "url": "http://httpbin.org/get?arg1=val1&arg2=val2"
}
2014-11-25 06:51:12