Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect a range of IPs using RewriteCond

Currently I am redirecting all users except for the IP 12.345.678.90 using:

RewriteEngine On RewriteCond %{REQUEST_URI} !/maintenance$ RewriteCond %{REMOTE_HOST} !^12\.345\.678\.90 RewriteRule $ /maintenance [R=302,L] 

What syntax would I use to allow a range? In my Allow list I have:

Allow from 123.45.678.90/28 

Would it work if I just update the REMOTE_HOST line to:

RewriteCond %{REMOTE_HOST} !^12\.345\.678\.90/28 
like image 399
xylar Avatar asked Jul 25 '12 15:07

xylar


2 Answers

If you're using Apache HTTPD 2.4 or later, you can use expressions to match REMOTE_ADDR against a CIDR mask.

The short form looks like this:

RewriteCond expr "-R '192.168.1.0/24'" 

The following longer form is also available, but the documentation suggests it is less efficient:

RewriteCond expr "%{REMOTE_ADDR} -ipmatch '192.168.1.0/24'" 

That makes the full solution to your example something like this:

RewriteEngine On RewriteCond %{REQUEST_URI} !/maintenance$ RewriteCond expr "! -R '12.345.678.90/28'" RewriteRule $ /maintenance [R=302,L] 
like image 145
zts Avatar answered Sep 23 '22 17:09

zts


You probably want the %{REMOTE_ADDR} to match against, but you can't use CIDR notation as the %{REMOTE_ADDR} is literally the remote address and you can use a regular expression to try to match against it. So for 123.45.67.89/28, (123.45.67.80 - 123.45.67.95), you'd have to do something like this:

RewriteCond %{REMOTE_ADDR} !^123\.45\.67\.8[0-9]$ RewriteCond %{REMOTE_ADDR} !^123\.45\.67\.9[0-5]$ 
like image 23
Jon Lin Avatar answered Sep 21 '22 17:09

Jon Lin