4.2
(171)

Last Updated on February 13, 2022 by Amit

With a RewriteRule directive you can deny access to a specific IP address or multiple ip addresses at the same time. If you need to deny access to a visitor IP address you can use a RewriteRule directive in htaccess file that checks the visitor IP address and blocks access to that address.
Blocking IP addressess using RewriteRule is as simple as ABC. You don’t need to do anything except using a RewriteRule in an htaccess file. In this post I will show you three RewriteRule examples that deny access according to visitors IP addresses.

Deny access to a specific IP address

To deny access to a single IP address you can use the following Rule in htaccess:

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^1.2.3.4.5$
RewriteRule (.*) - [F]

This will deny access to this specific ip address. Visitors having this ip addresses will get a forbidden error. You can also replace F with R=403 its same as F .

Deny access to multiple ip addresses

It is possible to deny access to multiple ip addresses at once using a single RewriteRule directive. If you have more then one ip addresses to deny access to, you can use a regex based pattern to match against those ip addresses, the following is a basic regex pattern to exclude 3 ip addresses, you can manully add more ip addresses to the pattern :

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^(1.2.3.4.5|ip2|ip3)$
RewriteRule (.*) - [F]

The pattern (.*) applies to the entire site including all files and folders , if you want deny access to a specific file path , say /user.php repace the (.*) with ^user.php$ or if the user.php file is located in /foo folder then use ^foo/user.php$ .

Block access to a specific path

To deny ip based access to a specific path you can use :

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^1.2.3.4.5$
RewriteRule ^thispath$ - [F]

This will forbid access to /thispath for a specific ip address matching the pattern 1.2.3.4.5 .

Hope this helps. Thanks for reading!

How useful was this post?

Click on a star to rate it!

Average rating 4.2 / 5. Vote count: 171

No votes so far! Be the first to rate this post.