Log visitors' IP addresses and protocol

By default, the target's web server log file only logs the load balancer's IP address.


In the log files of the web servers—the targets—only the load balancer's IP address is logged by default. This is because the load balancer is the one making requests to the web servers. However, it is possible to retrieve the visitor's IP address, as well as the protocol used, by reading two additional headers in the web server.

The Glesys load balancer adds the headers X-Forwarded-For and X-Forwarded-Proto.

X-Forwarded-For contains the IP address of the visitor, meaning the IP address that made the request to the load balancer.

X-Forwarded-Proto contains the protocol used when the visitor made the request to the load balancer. This will be either HTTP or HTTPS.

Apache2

In Apache2, add these two headers as custom fields in the access.log file by creating a custom LogFormat. This is done in the website's configuration file in Apache2, for example: /etc/apache2/sites-enabled/example.com.conf for the domain example.com (on Debian and Ubuntu).

example.com.conf
<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com
    ServerAdmin [email protected]
    DocumentRoot /var/www/html

    LogFormat "%h %l %u %t %{X-Forwarded-For}i %{X-Forwarded-Proto}i \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" loadbalancer
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log loadbalancer
</VirtualHost>

The name loadbalancer after the LogFormat and CustomLog lines is a name you assign to the log format. The format is based on the standard combined log format in Apache2, but here we have added the new headers after the timestamp. A log entry using this format might look like this:

Here, 203.0.113.81 is the IP address of the load balancer. The visitor's IP address is 198.51.100.96. The visitor used HTTP to connect to the load balancer.

PHP

Typically, you can display the visitor's IP address using PHP with the following snippet.

However, this will only display the IP address of the load balancer, since it's the load balancer that makes the request.

To display the visitor's IP address, you need to use the header X-Forwarded-For instead. The following PHP snippet will display the IP address of the actual visitor.

Last updated

Was this helpful?