Forwarding IP Address From Varnish to Apache On Ubuntu & CentOS

Varnish Logo

 

By default, varnish doesn’t forward the public IP of the visitor to the web server such as Apache or Nginx. This makes it harder to detect the visitors’ real IP and to read the log files since they will all be displaying the server’s IP.
To fix this, Varnish has to be configured to forward the real IP to the webserver.

Modify Configuration File:

Modify the Varnish /etc/varnish/default.vcl file:

vi /etc/varnish/default.vcl

Add or un-comment the following:

 sub vcl_recv {
if (req.restarts == 0) {
if (req.http.x-forwarded-for) {
set req.http.X-Forwarded-For =
req.http.X-Forwarded-For + “, ” + client.ip;
} else {
set req.http.X-Forwarded-For = client.ip;
}
}
}

Install Apache mod-rpaf for Apache below 2.4

Install on Debian/Ubuntu:

apt-get install libapache2-mod-rpaf

Enable mod-rpaf:

a2enmod rpaf

Configure it:
vim /etc/apache2/mods-enabled/rpaf.conf
<IfModule rpaf_module>
RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1 ::1 xxx.xxx.xxx.xxx
RPAFheader X-Forwarded-For
</IfModule>
Where xxx.xxx.xxx.xxx is the IP of the reverse proxy.. or just remove it if you use only 127.0.0.1

Install on CentOS:

Unlike Ubuntu, in CentOS, mod rpaf has to be compiled from source.

yum install httpd-devel

Download latest version of mod rpaf (0.6 by the time of this post):

wget  http://mirror.trouble-free.net/sources/mod_rpaf-0.6.tar.gz
tar zxvf mod_rpaf-0.6.tar.gz
cd mod_rpaf-0.6
apxs -i -c -n mod_rpaf-2.0.so mod_rpaf-2.0.c

Modify
vi /etc/httpd/conf.d/mod_rpaf.conf
and add:
RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1 xxx.xxx.xxx.xxx
RPAFheader X-Forwarded-For
Where xxx.xxx.xxx.xxx is the IP of the reverse proxy.. or just remove it if you use only 127.0.0.1

Install mod_remoteip for Apache 2.4 and above on CentOS:

If you’re using Apache 2.4 or above, you have to use mod_remoteip instead:

yum install httpd-devel
wget https://svn.apache.org/repos/asf/httpd/httpd/trunk/modules/metadata/mod_remoteip.c
apxs -cia mod_remoteip.c

Edit the Apache Configuration file:
Usually located in:

vi /etc/httpd/conf/httpd.conf

Below:

LoadModule remoteip_module    /usr/lib64/httpd/modules/mod_remoteip.so

Add:

RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy  127.0.0.1 xxx.xxx.xxx.xxx
RemoteIPProxiesHeader  X-Forwarded-For

Where xxx.xxx.xxx.xxx is the IP of the reverse proxy.. or just remove it if you use only 127.0.0.1

If you want to change the IPs that appear in the log file, scroll down a little bit and change the LogFormat from:

LogFormat “%i %l %u %t “%r” %>s %b “%{Referer}i” “%{User-Agent}i”” combined

to

LogFormat “%a %l %u %t “%r” %>s %b “%{Referer}i” “%{User-Agent}i”” combined

Restart Apache

(Ubuntu/Debian)

service apache2 restart

(CentOS)

service httpd restart

Questions? Please leave a comment below!

Leave a Reply

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