Admit it, a lot of your traffic is spambots. I know I see a lot of traffic from other countries to my blog for various reasons, and a good portion of them are SPAM. Blogging aside, what if you’ve got a community site that only a limited number of users will need access to? Well what about using that .htaccess for the purposes of keeping everyone else out!
That was the problem I ran into with one of my community sites. I was getting daily notifications of “new users” most of which were obvious combinations of a first-name/last-name dictionary attack, using out-of-country email addresses or free domain email addresses that require no invite, from IP addresses of non-community origin. I needed to remove the annoyance of these persistent email notifications. The solution was to eliminate access to the site from outside my community.
Step one was determining IP addresses. For my situation, I wanted to limit access to the entire United States. I did some searching and found a US zone file at IPdeny.com. Here is a listing of all countries they have zone files for. Step two was formatting the zone information such that it could be parsed through an Apache .htaccess file. I copied the zone information into a text document (using Notepad++), added the Limit clause to the top with the order clause below it, and set up a macro to add the allow from before each IP address on every line. After a portion of time, my macro completed and I added a deny from all line, and closed the Limit tag.
The result looked like this:
<Limit GET HEAD POST>
allow from 22.214.171.124/8
allow from 126.96.36.199/8
allow from 188.8.131.52/19
allow from 184.108.40.206/20
deny from all
At that point it was just a matter of saving the document out to my .htaccess file and testing. To do so, I searched the document for my IP block and commented it out with a ‘#’. I got a 403 Forbidden page, so I uncommented my IP block and tried again. PRESTO! Works like a charm.
A couple of other things you may want to do would include blocking a single country (instead of allowing a single country like I did) or to allow additional IPs through, in the case of someone unable to access using the list you obtained. To block a single country, you would change the “allow from” statements to “deny from” statements and use the IP addresses from that specific country. Some people would only like to block the most notorious countries (Nigeria, for example). In order to add a single IP address you create a new line, and put the IP address with a /32 on the end. You can add as many “allow from” or “deny from” IPs to this list as you desire.