Get client public ip on apache server used behind load balancer

December 4, 2017 1.8k views
Apache Load Balancing Ubuntu 16.04

We have to apache servers behind DO LB, is there any setting we need to do in LB or apache to get this as HTTP_FORWARDED_FOR, HTTPS_X_FORWARDED_FOR and REMOTE_ADDR are not working.

1 Answer

DigitialOcean Load Balancers set the X-Forwarded-For, X-Forwarded-Proto, and X-Forwarded-Port headers to give backend nodes information about the original request. For the original client's IP address to appear in your logs, you'll need to make a few configuration changes.

First, make sure that mod_remoteip is enabled. On an Ubuntu or Debian instance, you can do this with:

  • sudo a2enmod remoteip

Next, there are two changes that you will need to make to your Apache configuration (located at /etc/apache2/apache2.conf on Ubuntu and Debian). You'll need to add this line:

RemoteIPHeader X-Forwarded-For

As well as make an edit to the LogFormat line that matches the one used in your virtual host. By default that is the combined format. It would look like this in your virtual host config:

        CustomLog ${APACHE_LOG_DIR}/access.log combined

Find the matching LogFormat line in your Apache conf and change:

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

to:

LogFormat "%a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined

This tells Apache to log the client IP as recorded by mod_remoteip (%a) rather than hostname (%h). For a full explanation of all the options, see the Apache docs here.

For more information on configuring custom logging directives in Apache, check out:

by Justin Ellingwood
Apache can be configured to log a large quantity of information to help you diagnose problems and keep an eye on activity. In this guide, we will discuss how Apache handles logging and how you can create your own custom logging rules and rotation schemes.
Have another answer? Share your knowledge.