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

时间:2018-01-19 19:58:47

标签: 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";
  }

}

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

1 个答案:

答案 0 :(得分:6)

You can't do it using regular nginx directives but it's quite easy using 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.

Here's how to accomplish what you need:

  1. create a directory conf.d/
  2. put 2 files test.conf and header.lua into it (see the contents below)
  3. docker run -p8080:8080 -v your_path/conf.d:/etc/nginx/conf.d openresty/openresty:alpine
  4. curl 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

results

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)
)

Notice the X-Additional-Info header populated with the data obtained in /fetch_api handler