Question

Get client public ip on apache server used behind load balancer

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.

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

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:

  1. 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:

Will this work with LB configured for ssl passtrough?