Apache and X-Forwarded-For Headers


by Robert Cooper

As a follow on to my previous blog, its easier to get Apache to log client IP addresses utilizing X-Forwarded-For headers than it is using IIS. By default, the logs do not record source IP addresses for clients but this is very easy to change using the LogFormat directive in the httpd.conf file as explained below.

The standard LogFormat directive:
LogFormat “%h %l %u %t \”%r\” %>s %b” common

To add the clients source IP address, just change this to:
LogFormat “%h %l %u %t \”%r\” %>s %b %{X-Forwarded-For}i” common

To add the clients source IP address and put quotes around each field (useful when importing the logs into a spreadsheet or database):
LogFormat “\”%h\” \”%l\” \”%u\” \”%t\” \”%r\” \”%>s\” \”%b\” \”%{X-Forwarded-For}i\”" common

Once you’ve made the change, restart Apache and you’re done. The examples below show the resulting log entries for each configuration.

Standard logs:
192.168.2.210 – - [09/Feb/2011:09:59:31 +0000] “GET / HTTP/1.1″ 200 44

Client IP’s added:
192.168.2.210 – - [09/Feb/2011:10:00:16 +0000] “GET / HTTP/1.1″ 200 44 192.168.2.7

Client IP’s added and all fields encapsulated in quotes:
“192.168.2.210″ “-” “-” “[09/Feb/2011:10:01:10 +0000]” “GET / HTTP/1.1″ “200″ “44″ “192.168.2.7″

N.B.
192.168.2.210 is the IP of the Ethernet interface (eth0) on the load balancer
192.168.2.7 is the IP of my test PC

One other point, if you also have Pound SSL in your configuration, once you’ve added the X-Forwarded-For bit to your LogFormat directive, the logs will also record an additional entry for the Pound virtual server as shown below:

192.168.2.210 – - [09/Feb/2011:10:02:16 +0000] “GET / HTTP/1.1″ 200 44 192.168.2.7, 192.168.2.212

The  additional IP address (192.168.2.212) in this example  is the IP of the Pound Virtual Server.

One Response to “Apache and X-Forwarded-For Headers”

  1. Malcolm Turnbull Says:

    IVANCSÓ Krisztián said:
    I think there are more elegant ways:
    http://stderr.net/apache/rpaf/

    For Apache 2.3:
    http://httpd.apache.org/docs/2.3/mod/mod_remoteip.html

Leave a Reply

CAPTCHA Image Audio Version
Reload Image