【问题标题】:Can I modify inbuilt Nginx variable with Lua?我可以用 Lua 修改内置的 Nginx 变量吗?
【发布时间】:2017-04-08 16:22:44
【问题描述】:

nginx 日志格式为:

log_format  main  '$remote_addr [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$cookie_logintoken"';

我设置了 log_by_lua_file

log_by_lua_file xxxxx/ngx_lua_waf/log.lua;

和log.lua内容:

ngx.req.set_header("User-Agent", "this is testing User-Agent")
ngx.req.set_header("Referer", "this is testing Referer")

和 access.log 变化

127.0.0.1 [17/Dec/2016:16:21:47 +0800] "GET /test/client.php HTTP/1.1" 200 1370 "this is testing Referer" "this is testing User-Agent" "-" "-"

如何更改像 $request 这样的 nginx 内置变量?我想改变 "GET /test/client.php HTTP/1.1" 之前 nginx 登录到 access.log

ngx.var.request = "xxxx" 会出错:

failed to run log_by_lua*: xxxx/ngx_lua_waf/log.lua:15: variable "request" not changeable

但我不知道如何用 ngx.req.set_header 更改它

谁能告诉我怎么改?

【问题讨论】:

    标签: nginx lua openresty


    【解决方案1】:

    您可以使用 Nginx Lua 修改多个嵌入式 Nginx 变量,但需要修改嵌入式请求变量 cannot

    实际上,您的初始假设应该是嵌入式变量不能,或者更准确地说,不应该被修改。

    当您需要修改版本的嵌入变量时,定义一个自定义变量,对该自定义变量进行更改,然后改用它。

    在您的具体情况下:

        ### 
        ### Rewrite Phase ###
        ###
    
        #  Create your custom variable with a default value
        #  Runs before Log Phase so variable is available in Log Phase
        set $changed_request "-";
    
    
        ### 
        ### Log Phase ###
        ###
    
        ## log_by_lua* directives (Runs before inbuilt Log Phase directives)
        #  Update the custom variable etc
        log_by_lua_block {
            ngx.req.set_header("User-Agent", "this is testing User-Agent")
            ngx.req.set_header("Referer", "this is testing Referer")
    
            ngx.var.changed_request = ngx.var.request 
            -- Now do whatever changes you want to $changed_request.
        };
    
        ## Inbuilt Log Phase directives
        #  Define a custom log format with your custom variable
        log_format  customlogformat  '$remote_addr [$time_local] "$changed_request"'
            ' $status $body_bytes_sent "$http_referer" "$http_user_agent" '
            ' "$http_x_forwarded_for" "$cookie_logintoken"';
    
        #  Use your custom log format
        access_log /path/to/access.log customlogformat;
    

    【讨论】:

    • 似乎唯一的办法
    • 值得一提的是sethttp 上下文中无效,您应该在其他地方使用它(例如位置)。由于log_by_lua_block 在 nginx 日志阶段运行,因此无论您使用 set 定义变量的任何位置都应该可以工作。 nit:log_by_lua_block 之后没有;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 2018-09-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    相关资源
    最近更新 更多