How to set REMOTE_ADDR in apache before php is invoked

Not sure whether REMOTE_ADDR can be changed that way...


Actually, you might need to install / enable another Apache module, like mod_rpaf (quoting) :

It changes the remote address of the client visible to other Apache modules when two conditions are satisfied.
First condition is that the remote client is actually a proxy that is defined in httpd.conf.
Secondly if there is an incoming X-Forwarded-For header and the proxy is in it's list of known proxies it takes the last IP from the incoming X-Forwarded-For header and changes the remote address of the client in the request structure.
It also takes the incoming X-Host header and updates the virtualhost settings accordingly.
For Apache2 mod_proxy it takes the X-Forwared-Host header and updates the virtualhosts

Here's a blog-post about that : Nginx proxy to Apache - access remote host IP address using mod_praf

Update: original link not working right now, but it is available also as a debian package: apt-get install libapache2-mod-rpaf


I have solved this using mod_remoteip for Apache. mod_remoteip is for Apache 2.5 but thanks to this guy you can use it on Apache 2.2.x as well.

Download mod_remoteip.c from https://gist.github.com/1042237 and compile it with

apxs -i -a -c mod_remoteip.c

This should create mod_remoteip.so copy in the modules directory. apxs will also add LoadModule directive in your httpd.conf for newly created module.

Open httpd.conf and check does LoadModule directive for mod_remoteip exists

LoadModule remoteip_module    modules/mod_remoteip.so

Add RemoteIPHeader directive in httpd.conf

RemoteIPHeader X-Forwarded-For

This directive will instruct mod_remoteip to use X-Forwarded-For value from nginx as remote_addr. You can also use X-Real-IP instead:

RemoteIPHeader X-Real-IP

Restart the Apache. If you have set the proxy headers in nginx it will work like a charm and remote_addr in Apache will be correct

# nginx conf    
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Apache (requires mod_headers module):

SetEnvIf X-Real-IP "^(\d{1,3}+\.\d{1,3}+\.\d{1,3}+\.\d{1,3}+).*" XFF_CLIENT_IP=$1
RequestHeader set REMOTE_ADDR %{XFF_CLIENT_IP}e

REF for SetEnvIf RegEx: https://stackoverflow.com/a/10346093

Works also but doesn't verify input as IP:

SetEnvIf X-Real-IP "^(.*)" XFF_CLIENT_IP=$1
RequestHeader set REMOTE_ADDR %{XFF_CLIENT_IP}e

In PHP:

$_SERVER["HTTP_REMOTE_ADDR"]

-or-

$_SERVER["REMOTE_ADDR"]

No non-core Apache modules required

Tags:

Php

Apache