Redirect Visitors by IP Address

by richard on Wed, 2011-09-14 14:59

OK, so I was doing some work on my site, and wanting to redirect everyone but me to a separate version of the site (so I could play around as much as I wanted with the main version, and nobody would notice).

This is really easy, it turns out, using mod_rewrite in apache.

First, you need to know what IP address (or addresses) you want to exclude. This is fairly easy, just use a site like whatismyip to find out your external address.

Then comes the mod_rewrite magic.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.rf152.co.uk$ [NC]
RewriteCond %{REMOTE_ADDR} !^10\.20\.30\.40$
RewriteRule ^(.*)$ http://www2.rf152.co.uk/$1 [L,QSA]

The first line turns the rewrite engine on (you don't need to do this if it's already turned on further up)
The second line specifies the site you are directing away from (in my case, my main www site). This ensures that if, like me, the www2 is in a subsite of the www, then it doesn't create a redirection loop.
The third line is specifying the ip address to exclude. I have used 10.20.30.40, but if it was a live site, it would be an external one.
The final line is the line that actually does the rewriting. It says to redirect anything to www2.rf152.co.uk. The [L,QSA] part means that this will be the last rule applied, and it will attach the QueryString from the first request