How to get client IP address in logs instead of IP HAProxy

Once on the same server as HAProxy, I noticed that the server’s IP address is written in the logs, not the clients, or there’s simply no IP address at all and hyphens are displayed.

Since cPanel was still installed in the north, I looked at the Apache2 configuration file (/etc/apache2/conf/httpd.conf) and found:

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

Since clients open sites through Haproxy, so that Apache2 receives the real IP address of the client and writes it to the logs, you need to add one more thing:

%{X-Forwarded-For}i

That is, to get this:

LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

If pure Apache2 is installed on the server, then you can make changes to its configuration file, but if cPanel is used, then the configuration files cannot be edited directly, because changes can be erased, for example, after updating or editing the configuration via cPanel. Therefore, we’ll make this change not in the configuration file, but through the WHM menu “Service Configuration” – “Apache Configuration” – “Global Configuration”.

LogFormat (combined):

%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"

LogFormat (common):

%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b

You can verify the configuration by running the command:

httpd -t
apache2 -t

If there are no errors, then you can restart the web server to apply the changes, in WHM this can be done through the menu “Restart Services” – “HTTP Server (Apache)” or through the terminal with the commands:

service httpd restart
service apache2 restart

See also my articles:
Location of log files cPanel
Installing and Configuring the Apache2 Web Server

Leave a comment

Leave a Reply