Use htaccess to Block IP Address

In this tutorial we will show how to use an .htaccess file to block an IP address. This is one of several methods of blocking incoming requests to a web server. Other methods include blocking the IP address at the firewall or in PHP code, etc.

There are many reasons why you would want to block an IP address. It may be someone or something wasting or stealing your resources by making multiple requests to files on your server. It could be someone trying to spam your site. Whatever the reason for wanting to block an IP address, the htaccess file comes to the rescue.

Block a single IP address with .htaccess

The structure for the .htaccess file is simple. In it's simplest form it is:

order allow,deny
deny from 1.23.45.67
allow from all

Take care to replace 1.23.45.67 with the IP address that you want to block.

How it works is that we first set the order to "allow, deny", then we tell Apache who to deny, and then we tell it to allow everybody else. Requests coming from IP addresses that are denied will be answered with a 403 Access Denied HTTP header.

Block multiple IP addresses with .htaccess

If we have more than one IP addresses that we want to block, we just add a line for each address in our .htaccess file. Suppose we want to block IP addresses 1.2.3.4 and 2.3.4.5, we would do it like this:

order allow,deny
deny from 1.2.3.4
deny from 2.3.4.5
allow from all

You can add as many lines as you want; just follow the above template.

Block an IP address range with .htaccess

If we want to block a range of IP addresses we use something similar to what is below:

order allow,deny
deny from 123.45.67.
allow from all

Note that we left off the last digit of the IP address. This effectively makes it a wildcard match. So we would now be blocking everybody between 123.45.67.0 and 123.45.67.255 which is very powerful indeed. Take care when setting wildcards on blocks as you may very well block some legitimate clients.

Block clients by domain name using .htaccess

We don't even need to use numeric addresses to block clients. We can use domain names and subdomain names to block users. If we want to block all clients whose remote hostname ends in bad-isp-company.com, we could do this:

order allow,deny
deny from bad-isp-company.com
allow from all

This means that potentially all users from a particular internet service provider could be blocked.

This brings us to the end of this tutorial on using htaccess to block IP addresses. We hope you found it useful.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...