Admin Books

DOWNLOAD Free e-Books for Linux Admin Servers :

Get Real IP Address in server traffic from CLOUDFLARE-->VARNISH-->APACHE2

How can I log the client IP address on the backend?
All I see is the IP address of the varnish server. How can I log the client IP address?
We will need to add the IP address to a header used for the backend request, and configure the backend to log the content of this header instead of the address of the connecting client (which is the varnish server).
Varnish configuration:
sub vcl_recv {
  # Add a unique header containing the client address
  remove req.http.X-Forwarded-For;
  set    req.http.X-Forwarded-For = client.ip;
  # [...]
}
For the apache configuration, we copy the “combined” log format to a new one we call “varnishcombined”, for instance, and change the client IP field to use the content of the variable we set in the varnish configuration:
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" varnishcombined
And so, in our virtualhost, you need to specify this format instead of “combined” (or “common”, or whatever else you use):
<VirtualHost *:80>
  ServerName www.example.com
  # [...]
  CustomLog /var/log/apache2/www.example.com/access.log varnishcombined
  # [...]
</VirtualHost>

Getting Varnish, CloudFlare and Apache to play nicely with X-Forwarded-For can be a pain. However not setting this up right can cause serious PHP session problems with HTTPS requests passed through Varnish and CloudFlare to Apache. It also makes it hard to consistently get the real IP of users connecting via HTTP. This tutorial is a quick run-down on getting all of these things to play nicely and relay the real IP.

Now lets move on the Varnish. Edit your /etc/varnish/default.vcl to contain the following:
sub vcl_recv {
remove req.http.X-Forwarded-For;
if (req.http.cf-connecting-ip) {
    set req.http.X-Forwarded-For = req.http.cf-connecting-ip;
    } else {
            set req.http.X-Forwarded-For = client.ip;
        }


Those two simple steps will get Varnish to relay the real IP from CloudFlare to Apache in the form of X-Forwarded-For or X-Real-IP consistently over either the HTTP or HTTPS protocol whether or not CloudFlare is enabled for a given website on the server. If you have any thoughts, leave them in the comments below.