在向上游发送请求之前从API获取信息

Tho*_*mas 7 nginx

是否可以在位置块中发送http子请求并使用proxy_pass指令中的响应?

用例

我的上游应用程序需要API中的一些其他信息.我编写了一个使用proxy_pass指令代理请求的位置块.在nginx将请求发送到我的应用程序之前.我想向我的API发送一个HTTP请求,并使用几个响应头作为我的应用程序的请求标头.

这是我想要实现的概要:

server {
  server_name ...;
  location {
    # perform subrequest to fetch additional information from an api

    proxy_pass myapplication;

    proxy_set_header X-Additional-Info "some information from the subrequest";
  }

}
Run Code Online (Sandbox Code Playgroud)

该行为类似于auth_request模块.但是,我找不到使用标准nginx配置在位置块内发送额外阻塞HTTP请求的文档.

ffe*_*ast 7

您不能使用常规nginx指令来做到这一点,但是使用lua-nginx-module很容易。

该模块通过标准的Lua 5.1解释器或LuaJIT 2.0 / 2.1将Lua嵌入Nginx,并利用Nginx的子请求,将强大的Lua线程(Lua协程)集成到Nginx事件模型中。

这是完成您需要的方法:

  1. 创建一个目录 conf.d/
  2. 把2个文件test.conf,并header.lua把它(请参阅下面的内容)
  3. docker run -p8080:8080 -v your_path/conf.d:/etc/nginx/conf.d openresty/openresty:alpine
  4. 卷曲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;
    }
}
Run Code Online (Sandbox Code Playgroud)

头文件

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
Run Code Online (Sandbox Code Playgroud)

结果

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)
)
Run Code Online (Sandbox Code Playgroud)

请注意,X-Additional-Info标头中填充了在/fetch_api处理程序中获得的数据