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

Can I modify inbuilt Nginx variable with Lua?

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" "-" "-"

如何更改 nginx 内置变量,如 $request ?我想改变 "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修改多个嵌入的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;