Tuesday, October 7, 2014

How to Log Client IP AND X-Forwarded-For IP in Apache

When you use Load Balancer or any proxy in-front of you web servers, the visitor IP address is replaced with the load balancer or proxy IP. You will need to make the following changes in your apache config in order to retrieve the client IPs:

In your apache config (e.g. httpd.conf)

LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" proxy
SetEnvIf X-Forwarded-For "^.*\..*\..*\..*" forwarded
SetEnvIf X-Forwarded-For "^$" noforwarded


If you use a single log file, then change the CustomLog in httpd.conf:
CustomLog logs/access_log combined env=noforwarded
CustomLog logs/access_log proxy env=forwarded


If you are using separate log files for each domain, then you should change the CustomLog in your vhosts config:
CustomLog /log_location/domain-name.com-access_log combined env=noforwarded
CustomLog
/log_location/domain-name.com-access_log proxy env=forwarded