Server Administration & Management

How to redirect all users except your IP using .htaccess

Sometimes you didn’t want any visitors to see what you were doing, so you can set up a temporary blog at temp.mydomain.com. All you needed to do then was to redirect all visitors to that domain, but allow yourself to stay on the main domain of http://www.mydomain.com, and continue your maintenance work.

The solution was simple; You simply created a .htaccess file on your main domain, in the root folder. The htaccess contained the following information:

RewriteEngine on
RewriteCond $1 !^http://www.mydomain.com/temp
RewriteCond %{REMOTE_HOST} !^12.345.678.901
RewriteRule (.*) http://temp.mydomain.com/$1 [R=301,L]

It really is that simple to redirect all visitors, except you own IP, to a subdomain. The script above does the following:

1. Turn on the rewrite engine (no need to do this if it is already on in your htaccess).
2. Exclude the folder /temp from my rewrite (this is where the files for my subdomain are stored).
3. Exclude the IP address of 12.345.678.901 from my rewrite rule (you can find out your IP address by going to whatismyip).
4. I am then telling it to redirect everything (.*) to my subdomain http://temp.mydomain.com.

All you need to do is swap in the addresses for you subdomain files, your IP address, and your subdomain address. Simple as that!

April 20, 2012 Posted by | Firewall, htaccess | , , | Leave a comment