NGINX has a GeoIP module that can be leveraged to do various things based on GeoIP data for a remote host connecting to the NGINX server.
If not installed, install the NGINX libnginx-mod-http-geoip module.
apt install libnginx-mod-http-geoip
Add the following to your nginx.conf http block:
geoip_country /usr/share/GeoIP/GeoIP.dat;
Place the following configuration in /etc/nginx/conf.d/geoip-block.conf and adjust the ISO3 country codes to suit your needs. The example below blocks Russian Federation, China, Ukraine and Iran.
if ($geoip_country_code ~ "^(RU|CH|UA|IR)") {
rewrite / /geoip-block;
}
location /geoip-block {
default_type text/plain;
return 403 '$geoip_country_name IPs are blocked here.';
}
To block everything except US-based or Canadian-based IPs, change the if statement above to the following:
if ($geoip_country_code !~ "^(US|CA)$") {
rewrite / /geoip-block;
}
In your NGINX virtual host configuration file, for each virtual host you want to GeoIP block the countries, include the configuration in your server { } block.
include geoip-block.conf;