Knowledge Essentials - 3Essentials Hosting

How to block an IP address using a .htaccess file

Article ID: 2133

 Back to Search

How to block an IP address using .htaccess file

Applies to:  Linux based hosting plans only (Linux Shared, Linux Managed Servers)

The .htaccess file can be used to modify many website attributes on Unix and Linux servers.  This article describes how to use the .htaccess file to block IP addresses.  This can be useful for stopping traffic that is having a negative impact on the website or webserver.

To block IP addresses, block access to a domain, or just parts of a domain, add the following to the .htaccess file:

htaccess ip address block.png

This is an example of a .htaccess file that will block access to your site to anyone who is coming from any IP address beginning with 10.20.30. and from the specific IP address 192.168.207.154. By specifying only part of an IP address and ending the partial IP address with a period, all sub-addresses coming from the specified IP address block will be blocked. You must use the IP addresses to block access, as use of domain names is not supported.

Apache will start interpreting the Limit statement and will restrict access to the directory based on the directives between the Limit tags. The next line is the order directive, this tells Apache what order to process the allow and deny directives:

order allow,deny

In this case the allow directive will be processed before the deny directives. The order can be reversed. For example:order deny,allow. This would process the deny directives first than the allow directive.  The next line is a deny directive. This line tells Apache that all GET requests from anyone in the IP block of 10.20.30.* should be denied access:

deny from 10.20.30.

The next deny directive tells Apache that the IP address of 192.168.207.154 should be denied when making a GET request:

deny from 192.168.207.154

The final line tells Apache that a GET request from anybody else should be accepted and Apache should return the information being requested:

allow from all

Block an IP Address using mod_rewrite

Using mod_rewrite is an alternative method for blocking IP addresses with a .htaccess file. For example:

RewriteEngine on

RewriteCond %{Remote_Addr} ^192\.168\.168\.17$

RewriteRule ^(.*) http://localhost/ [R,L]

The following will block addresses between 192.168.0.0 and 192.168.255.255:

RewriteEngine on

RewriteCond %{Remote_Addr} ^192\.168

RewriteRule ^(.*) http://localhost/ [R,L]


 

 

 
Downloads Associated With This Article
No downloads are currently associated with this article.