How to redirect requests from particular IP addresses or networks with mod_rewrite

If you want to, you can redirect content only for requests that come from a certain IP address(es) or from a whole network of IP addresses. You can do this with a few mod_rewrite rules put in an .htaccess file on your hosting account.

For example, let's say that you want all requests from the IP address to to be redirected to, then you can put the following rules in the .htaccess file that's in the public_html directory on your hosting account:

#Redirect requests from a single IP address
RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^10\.20\.30\.45
RewriteRule ^index\.php$ /folder/index2.php [L]

When the client with the listed IP address opens, he/she will be redirected to Requests from all other IP addresses will not be redirected. This is achieved thanks to the RewriteCond directive that checks the remote address and if it matches the specified IP, then the RewriteRule is applied.

If you want to redirect requests from a couple or a few different IP addresses, you can include more RewriteCond directives and use the OR flag. For example:

#Redirect requests from a few different IP addresses
RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^10\.20\.30\.45 [OR]
RewriteCond %{REMOTE_ADDR} ^65\.220\.12\.31 [OR]
RewriteCond %{REMOTE_ADDR} ^125\.62\.81\.121
RewriteRule ^index\.php$ /folder/index2.php [L]

This will redirect requests to coming from any of the three listed IP addresses. Without the OR flag at the end of the first two RewriteCond directives these rules would be meaningless. The OR flag tells the RewriteRule that if any of the three conditions matches, then the redirect should be performed.

Of course, you can specify a whole range of IP addresses. Just use the first one to three numbers instead of the whole IP. For example:

#Redirect whole networks of IP addresses to an external URL
RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^10\.20\.30 [OR]
RewriteCond %{REMOTE_ADDR} ^125\.62
RewriteRule ^folder/(.*)$1 [R,L]

will redirect requests from all IP addresses starting with 10.20.30 and those that begin with 125.62. In the above example, unlike the previous ones, the redirect is to an external URL; request for resources inside are redirected to

It's also possible to make the redirect to apply to request from everybody except for the specified IP address(es) or ranges of IP addresses. This can be done by putting an exclamation mark before the pattern in the RewriteCond directive. For example:

#Redirect request for everybody except for the specified IPs
RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^10\.20\.30\.45
RewriteRule ^folder/(.*)$1 [R,L]

All requests for resources inside will be redirected to except for those requests that come from the IP address

For basic information on the mod_rewrite directives read the tutorial on mod_rewrite.

Was this answer helpful?

 Print this Article

Also Read