When working with web applications behind a reverse proxy or a load balancer, it becomes crucial to log the original IP address of the client, rather than the IP of the proxy. The X-Forwarded-For HTTP header is a standard solution to address this challenge, allowing the original IP address of a client connecting to a web server through an HTTP proxy or a load balancer to be captured and logged.

Apache, as a popular web server, can be configured to capture the X-Forwarded-For header value, providing better transparency about the traffic sources.

Many web servers and reverse proxies (like Nginx or HAProxy) automatically add this header. This guide will walk you through the process of ensuring that the Apache web server logs the X-Forwarded-For header value correctly.

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

  1. Open your Apache main configuration file or the configuration file for the specific virtual host you want to modify.

    $ sudo nano /etc/apache2/apache2.conf

    Location might vary depending on your OS and Apache installation.

  2. Locate the LogFormat directives. This directive defines the format in which Apache logs requests.
  3. Modify or add a new LogFormat to include the X-Forwarded-For header. A typical configuration would look like:

    LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i" "%{X-Forwarded-For}i"" combined
  4. Ensure that the CustomLog directive for your site or global configuration uses the log format you just defined or modified. For instance:

    CustomLog ${APACHE_LOG_DIR}/access.log combined
  5. Save your changes and exit the editor.
  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. Review the access logs to verify that the X-Forwarded-For IP addresses are being logged.

    $ 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.

By following these steps, you'll ensure that Apache correctly logs the original client IP address, providing clearer insights into your traffic sources and assisting in troubleshooting or monitoring tasks.