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

标签 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 中所做的事情。

想法?

My nginx -V output

最佳答案

你需要在 Lua 模块使用它之前定义变量 $foo 。查看the doc for an example defining the variable within the location directive在使用它之前。

关于nginx - 记录由 nginx 的 Lua 模块设置的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17663228/

相关文章:

laravel - CloudFlare SSL 证书无效

c++ - 为 C++ 构建 Lua

c++ - 在 Xcode 中设置 Lua 时遇到问题

nginx - Luasocket + nginx 错误 - lua 入口线程中止 : runtime error: attempt to yield across C-call boundary

java - Lua 堆栈溢出

ruby-on-rails - nginx http 代理状态 400 "400 Bad Request"带 SSL 客户端身份验证和 Rails

nginx - Docker Nginx 禁用默认暴露端口 80

redis - 无法识别的选项或args的参数数量错误: '--evalsha'

api - 我是否需要在前端和后端都使用 SSL

nginx:将单个静态 URL 映射到 PHP 文件