I have a web server behind a load-balancer.
I need to add a conditional redirect to my .htaccess in order to display a maintenance page whenever we take the site offline for maintenance. This part is straightforward:
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.php$ [NC]
RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif) [NC]
RewriteRule .* /maintenance.php [R=302,L]
However I want to add in a condition that if the visitor's IP address is my own, it will not redirect me to the maintenance page and that I would be able to see and test the site as if it was online. This part is normally also straightforward:
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^11\.111\.111\.111
RewriteCond %{REQUEST_URI} !/maintenance.php$ [NC]
RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif) [NC]
RewriteRule .* /maintenance.php [R=302,L]
However, because my web server is behind a load balancer, REMOTE_ADDR
is resolved to the internal IP address of the Load Balance server.
How can I alter this to look for the forwarded IP address? I know in PHP you can use $_SERVER['HTTP_X_FORWARDED_FOR']
to get the forwarded IP address. I've tried a few things in the .htaccess
but no luck:
%{X_FORWARDED_FOR}
%{HTTP:X_FORWARDED_FOR}
%{HTTP_X_FORWARDED_FOR}
SOLUTION
I got the following to work:
%{HTTP:X-FORWARDED-FOR}
Use
%{HTTP:X-FORWARDED-FOR}
instead of%{REMOTE_ADDR}
You need mod_rpaf. This module will rewrite REMOTE_ADDR in apache with another header, such as x-forwarded-for. Very useful for making PHP apps behave with load balancers.
http://blog.janjonas.net/2010-01-04/apaches-mod_rewrite-mod_proxy-use-reverse-proxy-request-headers-for-rewrite-rules
Might this be the answer?
If you have two environments, say one production behind the load balance and a development or staging not behind the load balance, and you want to use the same .htaccess file, you will need both %{HTTP:X-FORWARDED-FOR} and %{REMOTE_ADDR} -- assign IP addresses to both conditions.