.htaccess RewriteCond for REMOTE_ADDR while behind Load Balancer?
Solution 1
Use %{HTTP:X-FORWARDED-FOR}
instead of %{REMOTE_ADDR}
Solution 2
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.
Related videos on Youtube
Jake Wilson
Updated on September 18, 2022Comments
-
Jake Wilson over 1 year
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}
-
Jake Wilson over 12 yearsAll Caps worked for me. I guess it's not case sensitive or else it's an alias or something.
-
7heo.tk almost 8 yearsDo you really serve
.jpe
or.jp
files?
-
-
Ryan over 11 yearsI know you already answered it in your question, but you didn't have an answer below that matched. Thank you for your answer! Saved me today.
-
Andrew S about 11 yearsAlso, on some apache servers, the backslash will confuse the server. Simply put !^123.123.123.123 (without the backslashes, to mean if not IP 123.123.123.123) if you cannot get an iteration with backslashes to work.