记录Nginx Lua模块设置的变量

我试图在 nginx 中使用 Lua 模块根据请求的 JSON 设置一个变量(“foo”)。然后,我想将该变量的值记录到访问日志中。

如下所示:

http {
    log_format mylogfmt '$remote_addr - $remote_user [$time_local] \
        "$request" $status $body_bytes_sent "$http_referer" \
        "$http_user_agent" "$foo"'
}

location / {
    proxy_pass http://remote-server.example.com/;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_connect_timeout 150;
    proxy_send_timeout 100;
    proxy_read_timeout 100;
    proxy_buffers 4 32k;
    client_max_body_size 8m;
    client_body_buffer_size 128k;

    rewrite_by_lua '
        cjson = require "cjson"
        ngx.req.read_body()
        body_table = cjson.decode(ngx.var.request_body)
        ngx.var.foo = body_table["foo"]
    ';

    access_log /var/log/nginx/access.log mylogfmt;
}

但是 nginx 不会使用此配置启动,它会拒绝如下:

danslimmon@whatever:~$ sudo /etc/init.d/nginx reload
Reloading nginx configuration: nginx: [emerg] unknown "foo" variable
nginx: configuration file /etc/nginx/nginx.conf test failed

我尝试在位置上添加 'set $foo "-"',但那只是似乎覆盖了我在 Lua 中的操作。

有什么想法吗?

我的 nginx -V 输出

点赞
用户2647544
用户2647544

你需要在 Lua 模块可以使用之前定义变量 $foo。在使用之前,可以查看 文档中在 location 指令中定义变量的示例

2013-08-02 23:19:53
用户1100117
用户1100117

因为上面的链接不再起作用,所以要这样做:

  server {
    (...)
    map $host $foo {
        default '';
    }
    (rest of your code)
  }

这是因为你不能在服务器块中使用 set,这是定义变量对所有虚拟主机的最佳方法。geoip 也可能是一个不错的选择。

2017-06-26 19:13:05