Skip to main content

Restrict Site Access by Country (Geoblock)

Updated today

Sometimes it may be useful or required to restrict or redirect a visitor's access to a site based on what country the visitor is located in. Seravo has a feature integrated to do these restrictions, and here's how to configure it.

Restrict Access With PHP or nginx

Using the Seravo-specific HTTP header X-Seravo-Geo-Country-Code you can achieve more specific restrictions.

Forward Visitors to Another Site Based on Country Code With PHP

Useful e.g. if you have a multilingual site and you want to forward visitors directly to the correct language version.

<?php 
if (isset($_SERVER['HTTP_X_SERAVO_GEO_COUNTRY_CODE'])) {
switch (strtolower($_SERVER['HTTP_X_SERAVO_GEO_COUNTRY_CODE'])) {

// Forward Finnish visitors to example.fi
case 'fi':
header("Location: https://example.fi");
exit();

// Forward Swedish visitors to example.se
case 'se':
header("Location: https://example.se");
exit();

default:

// Do nothing, continue processing in WordPress
break;
}
} else {
error_log("Error: X-Seravo-Geo-Country-Code header not found!");
}

Country Code Based Redirect with nginx

The same can be implemented with the nginx web server.

# Redirect Finnish visitors to example.fi 
if ($http_x_seravo_geo_country_code = "FI") {
return 301 https://example.fi;
}

# Redirect Swedish visitors to example.se
if ($http_x_seravo_geo_country_code = "SE") {
return 301 https://example.se;
}

Login Page Restrictions With WP-CLI

It is also possible to set a location-based restriction for the WordPress login page. This feature is currently being implemented. Meanwhile, we recommend installing a reCaptcha plugin for login pages and making use of two-factor authentication (2FA) when logging in.

Edit the country codes in the example below to implement the desired restriction.

location ~ /wp-login.php { 
if ( $http_x_seravo_geo_country_code !~* "(FI|SE|BG)" )
return 403;
}
}

Further Reading

Read more on restricting access on your WordPress website from Seravo's Developer Docs.

Did this answer your question?