While I normally shy away from using Apache as a web server due to the many issues I hope most of you are aware of, I do still have servers that run it. I recently switched my server logging provider and ran into the problem that my Apache logs all display the IP address of my load balancer instead of the client’s IP address.

Now, this is much easier than most things involving Apache. All you need to do is make a few modifications to your Apache configuration files and voila, you’ll be logging the proper X-Forwarded-For address(if present) in no time.

Before we start, I will be assuming that you are on at least Apache v2.2.22 and are familiar with editing files on your server using the CLI.

If you look inside of your global Apache2 configuration file, located at /etc/apache2/apache2.conf, you’ll see a line that looks similar to this:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined

This is what you will be overriding inside of your virtual host file, which I’ll assume is located in /etc/apache2/sites-available/example.com. Inside of that file, there should be a few log file declarations already made, like this:

ErrorLog /var/log/apache2/error.log
LogLevel info
CustomLog /var/log/apache2/access.log combined

All we need to do is add the following lines to your file:

ErrorLog /var/log/apache2/error.log
LogLevel info
LogFormat "%h %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
CustomLog /var/log/apache2/access.log combined env=!forwarded
CustomLog /var/log/apache2/access.log proxy env=forwarded

Now simply restart apache:

sudo service apache2 restart

and you’re done.

If anyone is curious, the logging provider I chose to switch to is called PaperTrail. Their prices are reasonable and the setup was painless, I definitely recommend them to anyone looking to view all of their log files in one place.