Blog
July 2, 2015 Marie H.

Logging the correct IP to Apache over Varnish and Cloudflare

Logging the correct IP to Apache over Varnish and Cloudflare

Photo by <a href="https://www.pexels.com/@tima-miroshnichenko" target="_blank" rel="noopener">Tima Miroshnichenko</a> on <a href="https://www.pexels.com" target="_blank" rel="noopener">Pexels</a>

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:

  • Catch the Cloudflare and Varnish Headers and set the X-Forwarded-For header in the varnish configuration
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;
}
  • Setup the Apache LogFormat to use this header
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b" varnishcommon
  • Setup the ErrorLogFormat to use this header
ErrorLogFormat "[%t] [%l] [pid %P] %F: %E: [%{c}a] %M"
  • Setup the Apache vhosts to use the varnishcommon CustomLog

  • Restart Apache

service httpd restart