tags:

views:

314

answers:

3

I have a website set up with nginx acting as a reverse proxy to apache 2.2, which is running php. From apache and php's perspective the IP address of all requests is the nginx server. I'd like php to see the same remote IP that nginx sees.

Nginx sets a header X-Real-IP which contains the remote IP that nginx sees. I tried doing something like this in the apache conf:

SetEnvIf ^X-Real-IP$ "(.+)" REMOTE_ADDR=$1

My hope was that I could set the REMOTE_ADDR environment variable and when php finally gets invoked, it would see the remote IP that nginx sees. I think the php code is doing this:

$_SERVER['REMOTE_ADDR']

Anyway, this isn't working. Any ideas? Can you not set REMOTE_ADDR in the apache config file? Thanks.

+1  A: 

I don't know whether REMOTE_ADDR can be manipulated - it could be that it can't - but you should be able to get hold of the X-Real-IP header within PHP through something like

$_SERVER["HTTP_X_Real_IP"]

or similar - check phpinfo() for the correct notation.

Also, Apache environment variables set in .htaccess should be visible in PHP.

Pekka
+2  A: 

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

Pascal MARTIN
+1 Nice! This is good to know. Even though the module's name sounds like somebody hitting somebody else on the cheek in cartoon language :)
Pekka
As a sidenote : I've had never heard of that module ; not sure if it's well supported / stable / maintained / ... ;; *nah, the name sounds funny ^^ not necessarily a bad thing*
Pascal MARTIN
Pekka
used mod_rpaf and it worked like a charm. Thanks a lot!
Russell Neufeld
@Pekka : In french, we sometimes *(well, some years ago, actually)* say "Et paaaffff le chien" -- "and paf the dog" ^^ ;;; @Russell : good to know ! I myself have an apache server behing an nginx used as reverse proxy, and I faced the same problem *(but "solved" it by patching my PHP script)*
Pascal MARTIN
A: 

Off the cuff.. but could you pass the header X-Real-IP as a variable to the php using some rewrite magic..? Can't htaccess do stuff with header information before it invokes PHP?

danp