Configuring Apache and HAProxy to Record Clients’ Real IP Addresses

When hosting an Apache server behind an HAProxy, the server receives requests from the WAN through HAProxy. This method can pose a problem because your web server sees the proxy’s IP address for each request, making the logs almost unusable, and any WordPress security plugin might ban the proxy’s local address instead of the attacker’s address.

Fortunately, there is a way for the Apache server to correctly register the WAN address.

On the Apache server

Edit the Apache configuration file for the site:

nano /etc/apache2/sites-enabled/mysite.conf

Add the following directive:

RemoteIPHeader X-Forwarded-For
<VirtualHost *:443>
    ServerName mysite.com
    ServerAlias www.mysite.com
    DocumentRoot "/var/www/mysite"
    SSLEngine on
    SSLCertificateFile  /opt/cert.pem
    SSLCertificateKeyFile  /opt/key.pem
    RemoteIPHeader X-Forwarded-For
    <FilesMatch "\.(cgi|shtml|phtml|php)$">
        SSLOptions +StdEnvVars
    </FilesMatch>

    <Directory "/var/www/mysite">
        Options +FollowSymLinks
        AllowOverride all
        Require all granted
        SSLOptions +StdEnvVars
    </Directory>

    ErrorLog /var/log/apache2/error.mysite.com.log
    CustomLog /var/log/apache2/access.mysite.com.log combined
    LogLevel info
</VirtualHost>

Then, enable the RemoteIP module:

a2enmod remoteip

Restart Apache:

systemctl restart apache2

On the HAProxy server

Edit the HAProxy configuration file:

nano /etc/haproxy/haproxy.cfg

Add the following option to the Front:

option forwardfor
defaults
    log     global
    mode http
    option  httplog
    option  dontlognull
    option forwardfor
    maxconn 2000
    timeout connect 5000
    timeout client 50000
    timeout server 50000

Be careful not to use the source option in the backend. Here is an example:

backend backend_mysite
    cookie cookie_mysite insert nocache
    server mysite.com 10.10.10.1:443 ssl cookie stcookie02 weight 30

Finally, restart the HAProxy service:

systemctl restart haproxy

From now on, your Apache logs will contain the client’s IP address instead of the proxy’s IP address.

Leave a Comment