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:



I got the following to work:

  • %{HTTP:X-Forwarded-For} is the correct one. Is it case sensitive? Nov 10 '11 at 19:20
  • All Caps worked for me. I guess it's not case sensitive or else it's an alias or something. Nov 11 '11 at 15:49
  • Do you really serve .jpe or .jp files?
    – 7heo.tk
    Jul 15 '16 at 12:44


  • 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 9 '12 at 13:51

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.


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.

  • 1
    Also, on some apache servers, the backslash will confuse the server. Simply put !^ (without the backslashes, to mean if not IP if you cannot get an iteration with backslashes to work.
    – Andrew S
    May 8 '13 at 2:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.