4.8
(6)

Last Updated on February 13, 2022 by Amit

Deny access to a specific IP address with htaccess

With htaccess it is possible to block a specific IP address so that it can not access your website. You can block a specific part of your site or whole site for that spacific IP.
Blocking access to a client IP is useful when you don’t want your site to be available to them or if you are getting spam traffic from a client.
In this article , I will show you how to deny access to a specific client IP address using RewriteRule directive in htaccess file.

Suppose ,we are getting spam traffic from a client whose IP address is 125.55.77.8 and we want to block or deny access to this particular IP so that our website can not be visible to it. We can use PHP to restrict IP access but as you know PHP is per page context and it doesn’t apply to whole site. To set up a site wide restriction we need to use htaccess. We can use the following RewriteRule in our htaccess file to set up this restriction :

RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^125\.55\.77\.8$
RewriteRule .* - [F,L]

The rule will show a forbidden error to the restricted IP address if it tries to access your site.
The pattern .* means the whole site or all URLs . The F in flags section represents Forbidden error so the client will get an error with 403 status code.
If you want to block a specific URL on your site for an IP address , you can tweak the regex pattern . The following rule only applies to demo.php file meaning that only access to this file will be blocked.

RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^125\.55\.77\.8$
RewriteRule ^demo.php - [F,L]

If you want to block access to a directory and all files/folder inside that directory, you could use the following

RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^125\.55\.77\.8$
RewriteRule ^dirName/.* - [F,L]

I hope this article was helpful. If you have any questions about IP restriction , please post a comment below and wait at least 30 minutes to get my reply on the same page. Thanks for your time.

Related Post : Block access to multiple IP addresses using htaccess .

How useful was this post?

Click on a star to rate it!

Average rating 4.8 / 5. Vote count: 6

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