When using Apache behind a reverse proxy or load balancer, it is important to log the original client IP address rather than the proxy's IP. This can be achieved by using the X-Forwarded-For header, which records the originating IP address of the client. Configuring Apache to capture and log this header ensures accurate tracking of client requests.

Apache allows for the inclusion of the X-Forwarded-For header in its access logs through simple adjustments to the log configuration. By modifying the LogFormat directive, you can ensure that Apache logs reflect the true source of the traffic. This is particularly useful in environments with multiple proxy layers.

Accurately logging client IP addresses is critical for monitoring, auditing, and troubleshooting. Configuring Apache to log the X-Forwarded-For header is a straightforward process that improves the transparency of your server logs.

Steps to log X-Forwarded-For IP in Apache:

  1. Open the Apache configuration file for editing.
    $ sudo nano /etc/apache2/apache2.conf

    Location might vary depending on your OS and Apache installation.

  2. Locate the LogFormat directives in the configuration file.
  3. Modify an existing LogFormat or create a new one to include the X-Forwarded-For header.
    LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i" "%{X-Forwarded-For}i"" combined

    Add the expression %{X-Forwarded-For}i to the log format string. This expression tells Apache to capture and log the value of the X-Forwarded-For header for each request. Including this header in the log format ensures that the original client IP address is recorded in the access logs.

  4. Update the CustomLog directive to use the modified or new log format.
    CustomLog ${APACHE_LOG_DIR}/access.log combined
  5. Save the changes to the configuration file.
  6. Reload or restart the Apache service to apply the changes.
    $ sudo systemctl reload apache2

    Command may vary based on your operating system and Apache version. It's generally a good idea to use reload instead of restart to apply configuration changes without dropping connections.

  7. Verify that the Apache logs are capturing the X-Forwarded-For IP addresses by checking the access logs.
    $ tail /var/log/apache2/access.log

    Check the last lines of the log file to see recent access records and verify if X-Forwarded-For IP is correctly logged.

Discuss the article:

Comment anonymously. Login not required.