Logging the correct IP to Apache over Varnish and Cloudflare

Recently, during a side project I had to fix logging in Apache for Both Access Logs and Error Logs; Fortunately since Apache 2.4 you can also specify the ErrorLogFormat of your logs. The problem was that the client had clients with some over Cloudflare -> Varnish -> Apache and some over Varnish -> Apache and I needed to determine how to catch both and log properly.

The solution was as follows:

  1. Catch the Cloudflare and Varnish Headers and set the X-Forwarded-For header in the varnish configuration
  2. remove req.http.X-Forwarded-For;
    set req.http.X-Forwarded-For = client.ip;
    if ( req.http.CF-Connecting-IP ) {
        remove req.http.X-Forwarded-For;
        set req.http.X-Forwarded-For = req.http.CF-Connecting-IP;
  3. Setup the Apache LogFormat to use this header
  4. LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b" varnishcommon
  5. Setup the ErrorLogFormat to use this header
  6. ErrorLogFormat "[%t] [%l] [pid %P] %F: %E: [%{c}a] %M"
  7. Setup the Apache vhosts to use the varnishcommon CustomLog
  8. Restart Apache
  9. service httpd restart

Write a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.