Using .htaccess to block an IP Address
For whatever reason, there may come a time when you want or need to block an IP Address or domain name from accessing your website. There are a number of ways to do this and I will demonstrate these below.
You need to start off by creating a .htaccess file and placing it in the directory for which you want it to take affect on. For example, if you block access to example.com, you would place the .htaccess file in the root/home directory of your website. If you wanted to block access to example.com/myfiles, you would place the .htaccess file in the myfiles directory.
Once you have worked out what part of your website you want to block access to, you will need to add the following to the .htaccess file:
order allow,deny
deny from 203.101.101.101
allow from all
This will refuse all requests made by the IP address 203.101.101.101. An error message similar to the following will be shown instead.
Ok, so now lets say you wanted to block multiple IP Addresses from accessing your site. You simply list the IP Addresses one per line:
order allow,deny
deny from 203.101.101.101
deny from 203.101.101.102
deny from 203.101.101.103
allow from all
You also have the ability to block an entire IP Address range. You can do this by not specifying the last octet in the IP Address:
deny from 203.101.101
This will restrict access to anyone who falls in the 203.101.101 to 203.101.101.255 address range.
Instead of using IP Addresses to restrict access, you can also use domain names as well:
deny from example.com
You should be careful when using the .htaccess file to block an entire IP Address range or domain name as it’s likely to block access to genuine users. Where possible, and unless you have a specific need to block an entire range or domain name, you would be in most cases better off specifying individual IP Addresses or domain names.