2.7.1.1.9. Detect visitor country
Notes:
- For getting the country code in PHP, see Detect visitor country in PHP.
- To restrict access using hosting, see Country access restrictions.
A special nginx module adds a GeoIp-Country-Code header to each request to the site with a two-letter code of the visitor’s country (ISO 3166). The country is determined based on the visitor’s IP address according to MaxMind GeoLite data.
Below are solutions to some typical problems (in all examples, the specified lines must be added to the beginning of the .htaccess file in the site root directory):
Deny access to the site for all visitors from China:
RewriteEngine On
RewriteCond %{HTTP:GeoIp-Country-Code} ^(CN)$
RewriteRule .* - [F]
Deny access to the site for all visitors from Ukraine, except for a specific IP address or subnet:
RewriteEngine On
RewriteCond %{HTTP:GeoIp-Country-Code} ^(UA)$
RewriteCond expr "! -R '123.123.123.0/24'"
RewriteRule .* - [F]
Redirect visitors from Ukraine from the main page to the subdirectory /ua/:
RewriteEngine On
RewriteCond %{HTTP:GeoIp-Country-Code} ^(UA)$
RewriteCond %{REQUEST_URI} ^/$
RewriteRule .* /ua/ [L,R=302]
Deny POST requests (comments/site authorization/forum posting) from all countries except Ukraine and Poland:
RewriteEngine On
RewriteCond %{HTTP:GeoIp-Country-Code} !^(UA|PL)$
RewriteCond %{REQUEST_METHOD} POST
RewriteRule .* - [F]
Deny GET requests (page visits/site usage) from all countries except Ukraine and Poland:
RewriteEngine On
RewriteCond %{HTTP:GeoIp-Country-Code} !^(UA|PL)$
RewriteCond %{REQUEST_METHOD} GET
RewriteRule .* - [F]
تعليقات