Skip to content

Instantly share code, notes, and snippets.

@mortn
Last active April 24, 2024 16:55
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mortn/9407041 to your computer and use it in GitHub Desktop.
Save mortn/9407041 to your computer and use it in GitHub Desktop.
nginx geoip blocking with network exceptions.
# /etc/nginx/geoblocker
# This will block anything but the defined countries and the networks defined in the $localnet variable
set $geoblock 0;
if ($geoip_country_code !~ (DK|NO|SE)) { set $geoblock 1; }
if ($localnet = 1){ set $geoblock 0; }
if ($geoblock = 1){ return 403; }
# /etc/nginx/nginx.conf
http {
...
geoip_country /usr/share/GeoIP/GeoIP.dat;
# whitelist networks from geo ip blocking
geo $localnet {
default 0;
10.0.0.0/8 1;
192.168.0.0/16 1;
}
# the following line may already be in your nginx.conf
# conf files are in /etc/nginx/sites-available/*.conf and sym linked to ../sites-enabled/
include /etc/nginx/sites-enabled/*;
...
}
# /etc/nginx/sites-enabled/xample.com.conf
server {
server_name scandinavia.example.com;
# Apply geo blocking on this site by simply including the geoblocker file
include geoblocker;
...
}
server {
server_name .example.com;
# geoblocker not included so no blocking here
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment