是否可以在位置块中发送http子请求并使用proxy_pass指令中的响应?
用例
我的上游应用程序需要API中的一些其他信息.
我编写了一个使用proxy_pass指令代理请求的位置块.
在Nginx将请求发送到我的应用程序之前.我想向我的API发送HTTP请求并使用几个响应头
作为我的应用程序的请求标头.
这是我想要实现的概要:
server {
server_name ...;
location {
# perform subrequest to fetch additional @R_342_4045@ion from an api
proxy_pass myapplication;
proxy_set_header X-Additional-Info "some @R_342_4045@ion from the subrequest";
}
}
行为类似于auth_request module.但是,我找不到使用标准Nginx配置在位置块内部之前发送额外阻塞HTTP请求的文档.
解决方法:
你不能使用常规的Nginx指令来做到这一点,但使用lua-nginx-module很容易.
This module embeds Lua, via the standard Lua 5.1 interpreter or LuaJIT
2.0/2.1, into Nginx and by Leveraging Nginx’s subrequests, allows the integration of the powerful Lua threads (Lua coroutines) into the
Nginx event model.
以下是如何完成您的需求:
>创建目录conf.d /
>将2个文件test.conf和header.lua放入其中(参见下面的内容)
> docker run -p8080:8080 -v your_path / conf.d:/etc/Nginx/conf.d openresty / openresty:alpine
>卷曲http://localhost:8080/
test.conf
server {
listen 8080;
location /fetch_api {
# this is a service echoing your IP address
proxy_pass http://api.ipify.org/;
}
location / {
set $api_result "";
access_by_lua_file /etc/Nginx/conf.d/header.lua;
proxy_set_header X-Additional-Info $api_result;
# this service just prints out your request headers
proxy_pass http://scooterlabs.com/echo;
}
}
header.lua
local res = ngx.location.capture('/fetch_api', { method = ngx.HTTP_GET, args = {} });
ngx.log(ngx.ERR, res.status);
if res.status == ngx.HTTP_OK then
ngx.var.api_result = res.body;
else
ngx.exit(403);
end
结果
curl http://localhost:8080/
Simple webservice echo test: make a request to this endpoint to return the HTTP request parameters and headers. Results available in plain text, JSON, or XML formats. See http://www.cantoni.org/2012/01/08/simple-webservice-echo-test for more details, or https://github.com/bcantoni/echotest for source code.
Array
(
[method] => GET
[headers] => Array
(
[X-Additional-Info] => my-ip-address
[Host] => scooterlabs.com
[Connection] => close
[User-Agent] => curl/7.43.0
[Accept] => */*
)
[request] => Array
(
)
[client_ip] => my-ip-address
[time_utc] => 2018-01-23T19:25:56+0000
[info] => Echo service from Scooterlabs (http://www.scooterlabs.com)
)
请注意使用/ fetch_api处理程序中获取的数据填充的X-Additional-Info标头
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。