How to block or allow countries using GeoIP and .htaccess

From Brian Nelson Ramblings
Revision as of 14:38, 22 March 2018 by Brian (Talk | contribs) (Block Countries using GeoIP and .htaccess)

Jump to: navigation, search

How to block or allow countries using GeoIP and .htaccess

First you will want to to install GeoIP and mod_geoip

Block Countries using GeoIP and .htaccess

The following will deny from China, North Korea, South Korea

GeoIPEnable On
# Put countries to deny here      
SetEnvIf GEOIP_COUNTRY_CODE CN DenyCountry  
SetEnvIf GEOIP_COUNTRY_CODE KR DenyCountry  
SetEnvIf GEOIP_COUNTRY_CODE KP DenyCountry  

SetEnvIf GEOIP_COUNTRY_CODE <Country Code> DenyCountry

Allow from all  
Deny from env=DenyCountry

Allow Countries using GeoIP and .htaccess

The following will allow only from US, Canada and Mexico

GeoIPEnable On
# Put countries to allow here      
SetEnvIf GEOIP_COUNTRY_CODE US AllowCountry  
SetEnvIf GEOIP_COUNTRY_CODE CA AllowCountry  
SetEnvIf GEOIP_COUNTRY_CODE MX AllowCountry  
  
Deny from all  
Allow from env=AllowCountry  

Redirect to Specific page based on Country

The following will redirect United States and Canada traffic to the /USA folder

RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^(US|CA)$
RewriteRule ^(.*)$ http://www.mydomain.com/USA/$1 [L]

List of Country Code from Maxmind

http://dev.maxmind.com/geoip/legacy/codes/iso3166/