Friday, March 29, 2013

IP restriction in apache

You can use apache mod_rewrite to restrict access to your site.

For example, you can use the following code to restrict /images on your site to only allow ip address of 10.1.1.1. Any other ip will get a 403 forbidden error:

 RewriteEngine On
 RewriteCond %{REMOTE_HOST} !^10\.1\.1\.1$
 RewriteRule ^/images/ - [F]


If you need to allow an entire subnet such as 10.1.1.1 - 255, then you can use this:

 RewriteEngine On
 RewriteCond %{REMOTE_HOST} !^10\.1\.1\.(.*)$
 RewriteRule ^/images/ - [F]


If you need to allow a specific range such as 10.1.1.135-159, then you can use this:

 RewriteEngine On
 RewriteCond %{REMOTE_HOST} !^10\.1\.1\.13[5-9]$

 RewriteCond %{REMOTE_HOST} !^10\.1\.1\.1[4-5][0-9]$
 RewriteRule ^/images/ - [F]




If you are using load balancer, then you can replace %{REMOTE_HOST} with %{HTTP:X-FORWARDED-FOR} such as

 RewriteEngine On
 RewriteCond %{
HTTP:X-FORWARDED-FOR} !^10\.1\.1\.1$
 RewriteRule ^/images/ - [F]