问题陈述
我想基于请求标头中的某个值将proxy_pass转换为另一个url。所有请求详细信息,包括查询参数(如果有),标题和所有内容都应传递给代理地址。
我尝试了什么
我已经关注SO post并根据提到的要求我尝试了以下内容。
Test.lua文件
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
语句中手动传递查询参数。
如何通过在proxy_pass期间不传递实际request
来解决此问题?
答案 0 :(得分:2)
根据标题重写原始请求,可以轻松解决您的问题。 这是一个例子:
#sample backend
set $backend_host "http://httpbin.org";
location ~*/api/employees {
rewrite_by_lua '
--reading request headers
local req_headers = ngx.req.get_headers()
local target_uri = ""
-- checking an a header value to determine target uri
if req_headers["x-special-header"] then
target_uri = req_headers["x-special-header"]
else
-- default path if not header found
target_uri = "/get"
end
ngx.log(ngx.NOTICE, string.format("resolved target_uri: %s", target_uri))
--rewriting uri according to header (all original req args and headers are preserved)
ngx.req.set_uri(target_uri)
';
proxy_pass $backend_host;
}
示例请求发送'special'标头作为目标后端的路径:
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"
}
示例请求没有'特殊'标题:
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"
}