Ultimate Web Tips
your Wordpress, jQuery, PHP, MySQL, Linux and CSS guide to a successful website
Read more:

October 14th, 2011

How to block/allow IP addresses behind a load balancer with htaccess

Apache, by Joakim Ling.

Block IP behind an load balancer with htaccessWhen it comes to restrict your website, there are many ways to achieve that and one of the simplest methods is with your htaccess file. But it can be a little bit tricky when you’re in a cloud environment such as the Amazon Cloud and you are using the Elastic Load Balancer.

Normally you would put something like below to allow for two IP address

Order allow,deny
Deny from all
Allow from 11.11.11.11
Allow from 22.22.22.22

That works great as long as you don’t sit behind a load balancer, then the system will always think you are coming from the load balancers IP which we don’t want to block. Apache stores the client IP in an environment variable called X-FORWARDED-FOR, here’s an example to allow for the same IP addresses as above.

SetEnvIF X-FORWARDED-FOR "11.11.11.11" AllowIP
SetEnvIF X-FORWARDED-FOR "22.22.22.22" AllowIP
Order deny,allow
Deny from all
Allow from env=AllowIP

If you want to do the opposite and block just use “Deny from env=AllowIP”

There is also a second option with mod_rpaf which can alter the header and put the X-FORWARDED-FOR value in the Client IP.

Also be careful when using PHP and checking against remote IP, $_SERVER['REMOTE_ADDR'], in this case that will contain the load balancers IP. To get the real value try and use
$_SERVER['HTTP_X_FORWARDED_FOR'] instead.

Setting up a web server

Learn how to configure a web server from home, read more

Back Top

Club World Casinos
  • http://beerpla.net Artem Russakovskii

    Good call, thanks, was just wondering how to do that after switching to an nginx proxy.

  • Eric Ballet Baz

    Directive SetEnvIF uses RegExp so this is more correct :
    SetEnvIF X-FORWARDED-FOR “^11.11.11.11$” AllowIP

  • John M

    This is the article I have been looking for quite some time. Thank you for your help. Do you have any suggestions on how the same principles might apply if a htpasswd file is utilized (i.e. if IP = x, allow. If not within range, prompt with password from htpasswd file). If any satisfied, allow, else deny.