记录由nginx的Lua模块设置的变量

dan*_*mon 9 lua nginx

我试图在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;
}
Run Code Online (Sandbox Code Playgroud)

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

我尝试在该位置添加'set $ foo' - "',但这似乎超越了我在Lua中所做的事情.

思考?

我的nginx -V输出

Edd*_*Edd 5

在Lua模块可以使用之前,您需要定义变量$ foo.在使用它之前,请检查doc以获取在location指令中定义变量的示例.