Search code examples
.htaccesshttp-redirectmod-rewrite

How to redirect the request from specific IP address to another site with htaccess?


I am going to redirect some requests from specific IP addresses to another site. For example if the request come from xxx.xxx.xxx.xxx or xxx.xxx.xxx.xxy, I am going to redirect to https://example.com and for others, I am going to show my index.php.

So I tried like this, but this does not work.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteCond %{REMOTE_ADDR} xxx.xxx.xxx.xxx
    RewriteCond %{REMOTE_ADDR} xxx.xxx.xxx.xxy
    RewriteRule ^ https://example.com [L,R]
   
</IfModule>

Please help me.


Solution

  • You may use this code in your site root .htaccess:

    DirectoryIndex index.php
    RewriteEngine On
    
    RewriteRule ^index\.php$ - [L,NC]
    
    RewriteCond %{REMOTE_ADDR} ^xxx\.xxx\.xxx\.xxx$ [OR]
    RewriteCond %{REMOTE_ADDR} ^xxx\.xxx\.xxx\.xxy$
    RewriteRule ^ https://example.com [L,R]
    

    Important thing to note here is use of [OR] clause to allow matching any of the give IP addresses and use of anchors + escaping the dots to match IPs accurately.