2.7.1.1.9. Determination of the country of the visitor
Notes:
- You can restrict access to the site for different countries through «Access restriction»
- The way to get the country code in PHP is described here.
A special nginx module adds a header to each request to the site GeoIp-Country-Code
with the visitor's two-letter country code (ISO 3166). The country is determined based on the IP address of the visitor according to MaxMind GeoLite.
Below are the options for solving some typical tasks (in all examples, the specified lines must be added to the beginning of the file .htaccess in root directory of the site):
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]
Make a redirect from the main page to a subsection /ua/
for visitors from Ukraine:
RewriteEngine On RewriteCond %{HTTP:GeoIp-Country-Code} ^(UA)$ RewriteCond %{REQUEST_URI} ^/$ RewriteRule .* /ua/ [L,R=302]
Block POST requests (comments / authorization on the site / posting on the forum) from all countries, except for Ukraine and Poland:
RewriteEngine On RewriteCond %{HTTP:GeoIp-Country-Code} !^(UA|PL)$ RewriteCond %{REQUEST_METHOD} POST RewriteRule .* - [F]
Block GET requests (visiting pages / using the site) from all countries, except Ukraine and Poland:
RewriteEngine On RewriteCond %{HTTP:GeoIp-Country-Code} !^(UA|PL)$ RewriteCond %{REQUEST_METHOD} GET RewriteRule .* - [F]