简体   繁体   中英

Redirect visitors based on IP address

I have made a page that I want to protect with a IP address block.

Everybody that visits example.com should be redirected to example.com/block.php , unless there IP address is known to me. I want to be able to add a lot of IP addresses in a list somewhere. After I added the IP address of someone to the list, when they visit example.com again, they now should be redirected to example.com/index.php .

Is this possible? I have seen a lot of questions that look the same, but nothing that really answers my question.

There's several ways to do this, since you have the htaccess tag in your question, I assume you're looking for an htaccess file solution.

If you're not using apache 2.4 (or higher), you can use mod_authz to handle all of the blocking. Something like this:

# this makes it so blocked IPs get shown the block.php page
ErrorDocument 403 /block.php

Order Allow,Deny
Deny from all

Allow from 1.2.3.4
Allow from 1.2.3.5
Allow from 5.6.7.8

etc...

Here, you block everything and keep a list of "Allow from" lines. You can shorten them if you want to allow an entire subnet, eg

Allow from 1.2.3

will allow an IP starting with 1.2.3.

You can also use mod_rewrite for this:

RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^1\.2\.3\.4$
RewriteCond %{REMOTE_ADDR} !^1\.2\.3\.5$
RewriteCond %{REMOTE_ADDR} !^5\.6\.7\.8$
RewriteRule ^ /block.php [L,F]

Here, you have a bit more flexibility since you can use a regular expression to match the IP. So you can do stuff like:

RewriteCond %{REMOTE_ADDR} !^1\.2\.[3-6]\.

So this allows all IPs starting with: 1.2.3, 1.2.4, 1.2.5, and 1.2.6.

You can also put these directives into the server/vhost config file, it'll work a bit faster there instead of the htaccess file.

How about this?

<?php
$allowed = array(
    '123.45.67.890',
    '456.45.67.890',
    '789.45.67.890',
);

if(!in_array($_SERVER['REMOTE_ADDR'], $allowed)) {
    header("Location: /block.php");
    exit();
}

// continue with code ...

?>

Hope it works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM