Forum Moderators: phranque

Message Too Old, No Replies

How to redirect based on IP address

Redirect to another page based on a list of IP addresses

         

kektex

6:56 pm on Mar 9, 2006 (gmt 0)

10+ Year Member



Hello,
I did a search for this around the site since I was pretty sure this must have been asked before but found nothing.
I`ve got a list of IP addresses in this format :
58.14.0.0/15
58.16.0.0/13
58.24.0.0/15
[...]

What I want to do is use apache to redirect any of those IPs to another site, instead of accessing my main site.
The list is pretty big so I also have to be careful this doesn`t cause any extra "stress" on the server.
How can this be done with .htaccess?

Thanks!

jdMorgan

9:16 pm on Mar 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



kektex,

Welcome to WebmasterWorld!

The problem is that CIDR specifications are only understood by mod_access, which --as far as I know-- is only able to allow or deny access, i.e. either do nothing, or generate a 403-Forbidden response.

You can use mod_rewrite to do a conditional redirect based upon IP address ranges, but they have to be expressed as purely-text patterns (that is, with no numeric meaning).

So:


RewriteCond %{REMOTE_ADDR} ^58\.1[45]\. [OR]
RewriteCond %{REMOTE_ADDR} ^58\.(1[6-9]¦2[0-3])\. [OR]
RewriteCond %{REMOTE_ADDR} ^58\.2[45]\.
RewriteRule .* http://www.example.com/ [R=301,L]

would accomplish what you want for the examples you gave.

You could use an on-line CIDR-to-IP-range converter to make this job easier, but other than re-using the patterns you write for more than one line, there's not much that can be done short of writing a script to speed up the work.

Jim