How to set REMOTE_ADDR variable in Apache2 behind an nginx proxy

A lot of people are starting to put nginx in front of apache for performance and efficiency reasons.  Unfortunately, this causes problems for some web applications.  Especially anti-spam plugins or any other application that needs to know the client’s ip address. Plugins like bad behaviour and such. The reason for the problem is that the proxy is connecting to apache as localhost or an internal ip address.

I tried things like using setenv or requestHeader apache parameters but this did not work.

Finally I found an apache module, libapache2-mod-rpaf, that solves this problem quite nicely.

sudo apt-get install libapache2-mod-rpaf

You need to edit the /etc/apache2/mods-available/rpaf.conf file, and edit the RPAF_proxy_ips line, adding the address of your nginx proxy.

<IfModule mod_rpaf.c>
RPAFenable On
RPAFsethostname On
RPAFproxy_ips 192.168.0.1
</IfModule>

The example above is for a site that is behind an nginx server at 192.168.0.1.
EDIT: in order to get this to work on ubuntu 12.04 i had to remove the ifmodule mod_rpaf.c!!!

Be sure to set the X-Forwarded-For header in your nginx site config file’s server block

proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

If it is not working, you might find that you need to make a test.php file that contains

print_r($_SERVER)

That will help you see what is going on.

This entry was posted in nginx. Bookmark the permalink.

Comments are closed.