網頁

2018年9月21日 星期五

代理伺服器後的 Web Server 要取得 Client IP 的作法

這有一台主機是前端是透過 reverse proxy (squid) 代理,而這樣的方式若 Web Server 不做額外的調整時,所看到的連線記錄都會是 Proxy Server IP。如果要取得 Client IP 時,Apache就要做以下調整。

這是以 Apache2.4 windows server 為範例:

編輯 Conf/httpd.conf 檔案,內容如下:

啟用 LoadModule remoteip_module modules/mod_remoteip.so

將 LogFormat 所有出現 %h 改成 %a
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio

改成 
LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%a %l %u %t \"%r\" %>s %b" common
LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
(如果是直接在 $h 後加入 $a 那就會同時記錄proxy IP 與 client IP)
加入 
#To get Cient IP behide the Proxy
<IfModule mod_remoteip.c>
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy Your Proxy IP
</IfModule>

因為主機的使用量還蠻大的,所以主機有額外採用 rotatelogs 的機制,但很奇怪的是採用 TransferLog 的方式就不能記錄到 Client IP,記錄的 IP 還是 Proxy IP,但在 error.log 就有記錄到連線的 Client IP。後來將 TransferLog 改採 CustomLog 的方式後就可以正確的記錄 Client IP。

我在這卡了很久,一直不明白為什麼沒有記錄到 Client IP ,在後來才發現這個現象,只要將 TransferLog 的機制改成 CustomLog 後就可以解決這個問題。

修改方式如下:
TransferLog "|X:/Apache2/bin/rotatelogs.exe X:/Apache2/logs/access_%Y%m%d.log 2592000 common"
改成 
CustomLog "|X:/Apache2/bin/rotatelogs.exe X:/Apache2/logs/access_%Y%m%d.log 2592000" common

相關資料: