I couldn’t find a 100% working tutorial for this, so here we go. This is tested on Ubuntu 20.04
Install the packages
On your server:
add-apt-repository ppa:maxmind/ppa
apt update
apt install nginx-module-geoip geoipupdate
Configure updates
If you’re using unattended-upgrades, don’t forget to add the repository to /etc/apt.conf.d/50unattended-upgrades
. Look for this block (usually neat the start of the file):
Unattended-Upgrade::Allowed-Origins {
Add this line:
LP-PPA-maxmind:*";
Get an API key and configure Maxmind
First, get a free account at MaxMind:
https://www.maxmind.com/en/geolite2/signup?lang=en
Under ‘Manage License Keys’, create a new key. You do not need legacy support. Enter the key in /etc/GeoIP
.conf
AccountID <your account id>
LicenseKey <your license key>
# Make sure this is uncommented
EditionIDs GeoLite2-Country
Now run geoipupdate
Configure NGINX and your site
You will need to restart NGINX to load the geoip module (a reload is not enough):
systemctl restart nginx
Edit /etc/nginx/nginx.conf
, look for the section:
http {
Add the following to this section. Replace CA and US with the country codes you want to allow
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
CA yes;
US yes;
}
Now edit the file for yoursite. If you only have one site this might be /etc/nginx/sites-enabled/default
Look for this section:
server {
Add the following to this section:
if ($allowed_country = no) {
return 403;
}
You’re all done. Now just reload your NGINX config:
systemctl reload nginx
This command should return nothing. If you get an error, debug it by looking at:
systemctl status nginx
Did this tutorial work for you? Did you find it useful? Leave a comment below! I’m always happy to improve my articles.