1. 程式人生 > 實用技巧 >Nginx記錄使用者請求Header到access log

Nginx記錄使用者請求Header到access log

為了統計和其它用途,經常有人需要自定義Nginx日誌,把http請求中的某個欄位記錄到日誌中,剛好在看lua+nginx的文章,第一想到的是用lua賦值來做,但是想想有點小噁心,於是Google了一番,發現Nginx自己就能夠記錄收到的HTTP請求的頭部資料,測試如下方法可用。

測試環境Nginx 1.1.19

把自定義頭部加入日誌

為了方便,我們可能會在HTTP頭裡面加入特定的字串,做一些標示,如果需要把標示打到日誌裡面,其實很簡單。

在nginx的http段裡面對access log做如下的設定:

……
http {
……
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$http_mycheck"';
    access_log  logs/access.log  main;
……
}
……

我在日誌格式的最後面加入了$http_mycheck,那麼,Nginx會記錄mycheck這個頭部,儲存到access log裡面。

重啟Nginx,然後curl測試:

./nginx -s reload
curl -H "mycheck: justtestlog" localhost/whatever.html
curl localhost/whatever.html

然後檢視兩次請求的日誌記錄

tail -2 logs/access.log

127.0.0.1 - - [xxx] "GET /whatever.html HTTP/1.1" 200 21 "-" "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2" "-" "justtestlog"
127.0.0.1 - - [xxx] "GET /whatever.html HTTP/1.1" 200 21 "-" "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2" "-" "-"

請求頭部中沒有mycheck欄位的時候,日誌欄位裡記為"-",header有mycheck欄位的時候,最後一段是mycheck的值。

記錄使用者訪問的cookie

……
    set $dm_cookie "";
    if ($http_cookie ~* "(.+)(?:;|$)") {
        set $dm_cookie $1;
    }
 log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$http_mycheck" "$dm_cookie"';
 access_log  logs/access.log  main;
……

這樣日誌裡面就可以看到cookie了,據說可以監控使用者和行為。但是在實際中,cookie太長,加上cookie之後,日誌量會成倍增長,會加大伺服器的壓力,如非必要,不建議在日誌中新增該欄位。

記錄使用者訪問的$request_body

……
 log_format  main  '$remote_addr - $remote_user [$time_local] "$request" $request_body '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$http_mycheck" "$dm_cookie"';
 access_log  logs/access.log  main;
……

$request_body 變數已經增加到上述檔案裡面,可以記錄到客戶端請求體也就是域名後面進行的傳參值,記錄這個主要時判斷使用者名稱密碼一類的,建議生產伺服器也不要新增,日誌量會增大。