Redirect a range of IPs using RewriteCond

Viewed 55936

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
5 Answers

Although this is an old question, I find it still very relevant. An alternative that does allow CIDR notation is the following (example is in a virtualhost apache conf file):

<VirtualHost *:80>
    .
    .
    .
    <Files maintenance>
        Require all denied
        Require ip 12.345.678.90/28
    </Files>
    .
    .
    .
</VirtualHost>

As a sidenote, I suspect, without having done any testing or finding any evidence, that this method is "faster" than the RewriteCond expr "-R '192.168.1.0/24'" methods mentioned.

This is for the simple reason that at this high level there appears to be less computational steps involved.

N.B. a requester from an IP that is denied will see a "Permission denied" or "Forbidden" type response. You can make this prettier by adding in a custom 404 page that responding with a 200/OK (this way Google won't penalise your domain). The 200/OK has to be the first line of your custom 404 page. For example in PHP, the first line would read:

<?php header("Status: 200 OK"); ?>

You'd want to do this for a legit page you redirect to. Actual 404s should respond with 404 to keep us from ending up with a ton of useless search engine results down the road.

Try this in .htaccess. It's working.

RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.[0-255]
Related