This post will briefly describe how to configure Nginx on Alpine Linux to block certain countries from using your website. You can also check out this GitHub repository for a complete example.
Installing Nginx GeoIP module
To install the module, run:
apk --no-cache add nginx-mod-http-geoip
Please note that this is the old GeoIP module, not the paid-for GeoIP2 one that requires Nginx Plus.
Downloading GeoIP database
The GeoIP database has recently switched format to the mmdb
format, while the GeoIP module still uses the legacy dat
format.
There are ways of converting from mmdb to dat but luckily a user provides download of pre-converted files, so you can download the latest version from there.
Download the country database, unpack it and put it in the path /usr/share/GeoIPCountry.dat
Modifying nginx.conf
Modify your nginx.conf
file and add the following:
Inside http
block, add:
geoip_country /usr/share/GeoIPCountry.dat;
# Allowed proxy addresses
geoip_proxy 10.0.0.0/8;
geoip_proxy 172.17.0.1/16;
# List of disallowed countries
map $geoip_country_code $allowed_country {
default yes;
AL no;
BS no;
}
You will need the geoip_proxy
entries only if you are using Nginx in front of a reverse proxy / load balancer (like AWS ALB). For the ranges you include here, Nginx will look for the ip in the X-Forwarded-For
header, as opposed to the IP the request came from. If you don’t have such a setup you can remove those lines.
You will need to also modify the list of country codes from the examples which list Albania and Bahamas. You can find all country codes on this site.
Inside the server
block for your site, add the following:
# Add Country header for debugging
add_header X-Cntry "$geoip_country_code";
if ($allowed_country = no) {
return 444;
}
This will block the IP address by returning no content if the IP belongs to one of the blocked countries. It will also set a Header called X-Cntry
with the country code so that you can verify that everything works correctly. For example, you can now curl
your server and see the country code using this command:
curl https://your-site.com --HEAD --silent | grep -i X-Cntry
And the result will be something like:
X-Cntry: SE
Docker setup
You can also see a complete Docker example in this repository.
Notes / Acknowledgements
- https://www.howtoforge.com/nginx-how-to-block-visitors-by-country-with-the-geoip-module-debian-ubuntu
- Photo by delfi de la Rua on Unsplash