2016-12-17 479 views
0

nginx的日誌格式是:我可以使用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" "-" "-" 

如何像$ 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 

但我不konw如何與ngx.req.set_header改變它

誰能告訴我怎麼改?

回答

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; 
+0

似乎只有做 – weizhao

+0

方式,值得一提的是'set'不'htt'p上下文中有效,就應該在其他地方使用它(例如位置)。由於'log_by_lua_block'運行在nginx日誌階段,無論你使用set來定義變量都應該工作。 nit:log_by_lua_block後沒有';'。 – cuongnv23

相關問題