Redirect or deny site visitors based on IP using .htaccess

As a webmaster, there may be times when you want to deny one or more IP addresses or ranges from accessing your website. Be it comment spammers, page scrapers, or various other reasons. For that, you’re welcome to adopt the following code snippets. If you’ve found them helpful, or have something to share, please do so in the comments below.

Deny by IP

Start by looking for the following two lines in your .htaccess file

order allow,deny
allow from all

Add the following directives BETWEEN those lines. If you don’t have the above two lines, add them and the following lines between them.

# Throws a "403 Forbidden" for the matching IP ranges
# Matches 91.46.*.*
Deny from 91.46.
# Matches exactly
Deny from

Redirect by IP

Copy/paste the following code and add to your .htaccess file, changing the RewriteCond and RewriteRule lines to meet your needs. Read the comments.

# Permanently redirect based on IP rage
<IfModule mod_rewrite.c>
RewriteEngine On
# Try uncommenting this line if it doesn't take
# Options +FollowSymlinks
# The following line describe the IP-pattern to match
# If 1 octet is given, it will match the entire Class-A address
# If 2 octets are given, it will match the Class-B address
# if 3 octets are given, will match the Class-C address
# If 4 octets are given, will match the full address
# The NC directive means Not-Case-Sensitive. It's probably not required.
# Matches exactly
RewriteCond %{REMOTE_HOST} [NC,OR]
# Matches 10.2.*.*
# The trailing period is needed to prevent partial-octet matching
# (i.e. matching 10.200. or 10.20. instead of just 10.2.
RewriteCond %{REMOTE_HOST} 10.2. [NC,OR]
# OR statement must be on all but the last IP to match
# It means, literally, "match this rule, or..."
# Matches 10.5.6.*
RewriteCond %{REMOTE_HOST} 10.5.6. [NC]
# Next line format: RewriteRule <regex to match> <destination> <Flags>
# by default, the next line matches all URLs
# and permanently (301) redirects to the destination.
# Use R=302 instead for a temporary redirect.
# L means this is the last rule to process when this condition is met (recommended)
RewriteRule .* [R=301,L]

Thomas indicates that there should be a trailing backslash-period at the end of the 4th octet, if the octet is less than 3 digits. In testing, I haven’t found it necessary (and it behaves as expected), but readers are encouraged to try it both ways. If you find that one way works over another, feel free to share in the comments.

Here’s a simpler, albeit somewhat less flexible method. This doesn’t use the Apache rewrite module, nor pattern matching, and may or may not fit your needs.

# 301 (permanently) redirect requests for /bar to
301 redirect /bar
# Also redirect the web root
301 redirect /

Questions, comments, and feedback regarding these methods are welcome and apreciated. Have something to contribute, or have feedback about the above code? Please feel free to share in the comments below!


, ,