How to Redirect All Except Your IP Address using .htaccess


redirect all except ip address to different page

Sometimes, you may need to redirect all IPs to a different page, except a few known IP addresses or address ranges. .htaccess allows you to redirect all except a few IP addresses without modifying server config file. Here’s how to redirect all except your IP address using .htaccess.

 

How to Redirect All Except Your IP Address using .htaccess

Here are the steps to redirect all except your IP address using .htaccess. Before proceeding, please ensure that you have enabled mod_rewrite (.htaccess) in your Apache web server.

 

1. Open .htaccess file

Open .htaccess file in a text editor. It is generally located at /var/www/html


$ sudo vim /var/www/html/.htaccess

 

2. Redirect All Except Your IP

Let’s say you want to redirect all IPs except yours (192.168.0.1) from /login.php to /product-page.php. So add the following lines to your .htaccess file.


Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !=192.168.0.1
RewriteRule login.php$ /product-page.php [R=301,L]

In the above code, the first 2 lines enable URL redirection

The next line checks if the IP is not your IP

The next line executes the redirection, if the above condition matches.

 

If you need to allow multiple IPs, you can use the ‘|’ operator as shown below


Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^127.0.0.1|192.168.0.1
RewriteRule login.php$ /product-page.php [R=301,L]

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

 

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!