Block IP Addresses by Country

by tyler on April 12, 2008

One of the worst things about being a webmaster is the constant battle we wage against spammers and scrapers. A majority of these creeps have IP addresses which originate from outside the United States in countries like China, Russia, Latvia and Nigeria.

After years of being a webmaster, I have found that a majority of these countries send only bots and other nefarious users to my sites. So I use htaccess IP banning to handle these net-scumbags most of the time.

IP banning in a htaccess file looks like this:

<Limit GET HEAD POST>
order allow,deny
deny from 202.70.112.0/20
allow from all
</LIMIT>

There are many services online that will give you IP CIDR block listings by country such as IPDeny, Block a Country and Country IP Blocks. The last two will actually generate the htaccess deny statements for you, which is a huge time saver.

If you ever find the need to block country IP’s, be sure to check out the sites above.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

{ 3 comments… read them below or add one }

Dawn Young October 1, 2009 at 10:40 pm

Besides IPDeny, Block a Country and Country IP Blocks, IP2Location also offers the free blocking service.

http://www.ip2location.com/blockvisitorsbycountry.aspx

I personally prefer IP2Location because they have more up-to-date IP Country Database.

Just my personal opinion.

Reply

Delerium October 22, 2009 at 2:29 pm

I disagree with Dawn Young, merely on the fact that IP2Location will only give 1 country per listing anonymously, and 30 per country if you register with them. As I hate registering for a site just to use something one time, I find the others much more user friendly, even if they aren’t up to date. Likewise another solution would be to make a php script that checked the country of the IP address visiting, and banned accordingly. It could even create a log of IP ranges for you to put into htaccess.

Reply

Dmitry Dulepov January 2, 2012 at 1:30 pm

You can do that also with mod_security to really block by country. Typical rule:

SecRule REQUEST_URI “.*” “chain,drop,logdata:’Country is: %{geo.country_code} (%{geo.city})’”
SecRule REMOTE_ADDR “@geoLookup” “chain”
SecRule GEO:COUNTRY_CODE “@pm A1 AP BR CN RU”

The first two country codes are special: anonymous proxies, etc.

Reply

Leave a Comment

Previous post:

Next post: