如何在代理通过后发出http请求?使用openresty(lua + nginx)

我有与https://github.com/openresty/lua-nginx-module/issues/220类似的需求。

我的使用场景

  1. 我正在通过使用proxy_pass将文件转发到远程服务器。
  2. 我需要在代理通过后将$body_bytes_sent传递到远程url。
  3. 我考虑使用content_by_lua块,其中ngx.capture转发到proxy_pass块,ngx.say()返回来自ngx.capture的内容。然后请求具有$body_bytes_sent的远程url。但是我需要支持流,这不会做到。而且文件可能会变得非常大,这对于ngx.capture()来说不好。
  4. 我考虑使用log_by_lua块,但是cosockets apis已禁用。 https://github.com/openresty/lua-nginx-module#log_by_lua
点赞
用户2741393
用户2741393

安装 Lua-Curl 或者其他不依赖于 cosockets 的库。 (https://github.com/Lua-cURL/Lua-cURLv3)

如果你正在使用 luarocks(openresty 自带),可以使用以下命令进行安装:

apt-get install libcurl3 libcurl3-gnutls libcurl4-openssl-dev --yes
luarocks install Lua-cURL

使用 log_by_lua(例如 log_by_lua_blocklog_by_lua_file),操作如下。

# 一些 nginx 配置

location /a_location_with_proxy_pass {
    proxy_pass https://example.com:443;
    log_by_lua_file /path/to/luafile.lua;
}

你的 log_by_lua_file 应当向远程服务器发起 curl 请求。

local cURL = require 'curl'

curlHandle = cURL.easy{
    url        = 'https://remote_host.com/endpoint',
    post       = true,
    httpheader = {
        'Content-Type: application/json';
    },
    postfields = '{"bytes":' .. ngx.var.body_bytes_sent .. '}'
};
curlHandle:perform();
2017-08-23 00:04:38