我可以用Lua修改内置的Nginx变量吗?

时间:2016-12-17 08:43:53

标签: nginx lua openresty

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内置var?我想改变 在nginx登录到access.log

之前“GET /test/client.php HTTP / 1.1”

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

更改它

谁能告诉我如何更改它?

1 个答案:

答案 0 :(得分: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;