0

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 内置变量?我想将 nginx 日志之前的“GET /test/client.php HTTP/1.1”更改为 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 更改它

谁能告诉我如何改变它?

4

1 回答 1

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;
于 2016-12-17T09:48:12.940 回答