Dave Perrett

Passing IPs to Apache With Nginx Proxy

apache, linux, nginx, programming, web

When you use nginx to proxy to apache , apache picks up the IP address of your nginx proxy as the client. A consequence of this is that apache log files, and any application running on the apache backend, will all receive the same IP address (for example 127.0.0.1 if apache and nginx are running the same server).

Luckily, nginx provides a HTTP X-Forwarded-For header containing the clients real IP address, although apache doesn’t pick it up by default. To allow apache to recognize the original client IP, we need to install the mod_rpaf module. On ubuntu, this is as simple as installing a package :

1
> sudo apt-get install libapache2-mod-rpaf

Once you have installed mod_rpaf, you need to configure apache. Add something similar to the following to your apache config (alter the RPAFproxy_ips setting as appropriate to match the IP address(es) of your nginx server(s) :

1
2
3
4
5
<IfModule mod_rpaf.c>
RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1
</IfModule>

If you installed the ubuntu package, this should be set up for you automatically in /etc/apache2/mods-available/rpaf.conf .

Once apache is restarted, you should be able to see the correct IP addresses in the apache access logs.

If nginx has trouble passing the X-Forwarded-For header for some reason, you can try to force it to set headers by hand :

1
2
3
4
5
...
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
...