在我看来,最简单的方法是使用 lua。content_by_lua、rewrite_by_lua、access_by_lua 或它们的任意组合之间的选择;将取决于您如何使用子请求的响应正文。该决定还将确定您是否需要其他位置。
这里有几个例子:
1. 使用 content_by_lua 定位本地位置。
(这种方式需要定义子请求位置)
location /original/url {
lua_need_request_body on;
content_by_lua '
--Lots of params but I only need 5 for the subrequest
local limited_post_args, err = ngx.req.get_post_args(5)
if not limited_post_args then
ngx.say("failed to get post args: ", err)
return
end
local subreq_uri = "/test/local"
local subreq_response = ngx.location.capture(subreq_uri, {method=ngx.HTTP_POST,
body = ngx.encode_args(limited_post_args)})
ngx.print(subreq_response.body)
';
}
location ~/test/local {
lua_need_request_body on;
proxy_set_header Accept-Encoding "";
proxy_pass http://echo.200please.com;
}
2. rewrite_by_lua 到远程目标
(不需要额外的位置)
location /original/url/to/remote {
lua_need_request_body on;
rewrite_by_lua '
--Lost of params but I only need 5 for the subrequest
local limited_post_args, err = ngx.req.get_post_args(5)
if not limited_post_args then
ngx.say("failed to get post args: ", err)
return
end
--setting limited number of params
ngx.req.set_body_data(ngx.encode_args(limited_post_args))
--rewriting url
local subreq_path = "/test"
ngx.req.set_uri(subreq_path)
';
proxy_pass http://echo.200please.com;
}
带有 7 个参数的示例发布请求限制为 5 个:
curl 'http://localhost/original/url/to/remote' --data 'param1=test¶m2=2¶m3=3¶m4=4¶m5=5¶m6=6¶m7=7' --compressed
回复:
POST /test HTTP/1.0
Host: echo.200please.com
Connection: close
Content-Length: 47
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
Accept: */*
Accept-Encoding: deflate, gzip
Content-Type: application/x-www-form-urlencoded
param3=3¶m4=4¶m1=test¶m2=2¶m5=5