Apache: getting remote IP when working behind nginx

Sometimes you may want to use Apache behind nginx. In this case nginx works as reverse proxy and handles user connections and static files. And Apache generates dynamic content (for instance, with use of PHP). In this case remote IP in your scripts would be 127.0.0.1 since Apache gets requests from the same server. It could lead to some problems with your application. For example, if you add to ban list IP addresses from your application there could get address 127.0.0.1. To solve this issue you can use header X-Forwarded-For which nginx will add to it requests. But sometimes you don’t want or can’t modify your code. In this case you can use Apache module rpaf which solves this problem. Here is how to setup it on Centos 6.2.

Firstly you need to set up headers in your nginx location:

proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

To install module we need to rebuild it from srpm package. You can get it from this repository.

wget http://rpms.southbridge.ru/stable/SRPMS/mod_rpaf-0.6-1.southbridge.src.rpm

Rebuild:

rpmbuild -bb ~/rpmbuild/SPECS/mod_rpaf.spec

And install:

rpm -ivh ~/rpmbuild/RPMS/x86_64/mod_rpaf-0.6-1.southbridge.x86_64.rpm

Add to your Apache config file:

LoadModule rpaf_module modules/mod_rpaf-2.0.so

RPAFenable on
RPAFsethostname Off
RPAFproxy_ips 127.0.0.1 <your external IP>

RPAFheader X-Real-IP

After Apache restart it should start getting correct remote IP of user. To make sure check its access logs.