2014-07-11 105 views
0

我想基於某個自定義響應頭來記錄請求主體。所以,假設服務器正在發送TEST-HEADER: value。現在我必須檢查這個header的存在,並在nginx中對access_log做一些操作。

我的配置是如下:

log_format test '$remote_addr - $remote_user [$time_local] "$request" ' 
       '$status $body_bytes_sent "$http_referer" ' 
       '"$http_user_agent" "$http_x_forwarded_for" "$request_body"'  
       '"$sent_http_test_header"'; 

location/{ 
     proxy_pass http://app_server$request_uri; 
     access_log logs/access.log main; 
     set $a $sent_http_test_header; 
     if ($a) { 
      access_log logs/host.access1.log test; 
     } 
    } 

這裏,$sent_http_test_header$upstream_http_test_header變量的值永遠不會設置。所以如果塊永遠不會被執行。

如果我使用$status variable,它工作正常。

這裏可能有什麼錯誤?

+0

重寫規則在代理之前執行,因此在執行'if'時沒有'$ upstream _...'變量。你可以使用['access_log'](http://nginx.org/r/access_log)指令的nginx 1.7和'if'修飾符。 –

+0

@AlexeyTen有沒有辦法在nginx 1.6.0中做。因爲nginx 1.7是最新版本,我們沒有在生產中使用。我們使用穩定版本1.6。 –

+0

我不知道那樣做 –

回答

0

Alexey Ten所述,if在重寫階段(在內容之前,例如代理)運行,set也如此運行。究竟是什麼你問能不能與nginx的1.6來完成,無需額外的模塊,但你有可能會解決你的問題,有兩種選擇:如果你有

或可以在LUA模塊添加到您的nginx,你可以這樣做:

location/{ 
    set $extra_log dev/null;                  
    # We want the lua code to be run before the log phase, header_filter_by_lua 
    # works fine. 
    header_filter_by_lua ' 
     if ngx.header.test_header then 
      ngx.var.extra_log = "full_path_without_leading_slash/host.access1.log" 
     end 
    '; 
    # ... the rest of your config ... 
    access_log /$extra_log test; # note/before variable to let nginx know it's 
            # an absolute path 
} 

如果沒有lua,您可以在access_log路徑中使用$sent_http_test_header,但這會導致用於日誌文件路徑的標頭的整個值,而不僅僅是變量的存在(並且您將得到一個日誌文件即使值爲空)。這看起來像:

location/{ 
    # ... the rest of your config ... 
    access_log logs/$sent_http_test_header.log test; 
}