13

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
  • 8,494
  • 29
  • 94
  • 121

4 Answers4

13

Use %{HTTP:X-FORWARDED-FOR} instead of %{REMOTE_ADDR}

Ryan
  • 410
  • 2
  • 8
  • 16
  • I 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. – Ryan Oct 09 '12 at 13:51
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.

Matthew Ife
  • 22,927
  • 2
  • 54
  • 71
0

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.

Andrew S
  • 510
  • 4
  • 7
  • 1
    Also, 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. – Andrew S May 08 '13 at 02:16