Block IP Addresses and Countries using .htaccess

  Print

Block IP Addresses and Countries using .htaccess

If you’re getting too much unwanted traffic from certain IP’s, a handy tool is the IP blocking feature of .htaccess file (click here for a tutorial on seeing which IP’s hit your site). This file is located in the public_html folder of your primary domain, and the primary folder of any subdomains and add on domains. Just add the following code to the top of your file:

order allow,
deny deny from 144.5.56.77
deny from 12.34.23.107
allow from all


You can also do the reverse, and allow only specific IP’s to be allowed on your site:


order deny,allow
deny from all
allow from 211.35.214.13


What if the unwanted visitor is from a different country and keeps changing their IP? Provided your website isn’t intended for visitors from that country, you can easily use the GeoIP tool to block that country. Just add the below code to the top of your .htaccess file.



GeoIPEnable On
# Add countries you wish to deny here
SetEnvIf GEOIP_COUNTRY_CODE CO DenyCountry
SetEnvIf GEOIP_COUNTRY_CODE EG DenyCountry
SetEnvIf GEOIP_COUNTRY_CODE HI DenyCountry
Allow from all
Deny from env=DenyCountry



You can also do the opposite and only allow specific countries to access your website. This is a great proactive security measure if, for example, you only intend to have Australian clients or visitors to your site.



GeoIPEnable On
# Put countries to allow here
SetEnvIf GEOIP_COUNTRY_CODE AU AllowCountry
SetEnvIf GEOIP_COUNTRY_CODE NZ AllowCountry
Deny from all
Allow from env=AllowCountry


A list of all country codes can be found bellow or at their original source here:http://dev.maxmind.com/geoip/legacy/codes/iso3166/




Related Articles