2.12.9. Determining 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.
Each site request contains a special header GeoIp-Country-Code
which contains the visitor's two-letter country code (ISO 3166). The country is determined based on the visitor's IP address as reported by 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 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 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]