Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jezman/2dcd16ff43d392c19a3128a4fa566cdd to your computer and use it in GitHub Desktop.
Save jezman/2dcd16ff43d392c19a3128a4fa566cdd to your computer and use it in GitHub Desktop.
Allow or block GeoIP except LAN in Nginx on Debian 12

GeoIP Block NGINX Debian 12

Block or filter IPs based on location except lan ips in Nginx (tested on 1.22.1) on Debian 12.

Install Nginx modules

To make use of the geographical filtering, we must first install the Nginx GeoIP module as well as the GeoIP database containing the mappings between visitors’ IP addresses and their respective countries. To do so, let’s execute:

$ sudo apt install libnginx-mod-http-geoip geoip-database

Edit nginx config /etc/nginx/nginx.conf. Add this below the http { line to only allow Russian IPs You can use ISO’s full, searchable list of all country codes to find your code.

    # lan IPs
	geo $lan {
		default	0;
		1.2.3.4 1;
	}

	# GeoIP database path
	geoip_country /usr/share/GeoIP/GeoIP.dat;

	# Allowed country codes
	map $geoip_country_code $allowed_country {
		default	0;
		RU	1;
	}

	map $lan$allowed_country $deny {
		default 0;
		00	1;
	}

Finally, add this to your sites virtual config /etc/nginx/sites-enabled/siteconfig below server {:

    if ($deny) {
        return 503;
    }

Check Nginx config sudo nginx -t

Reload Nginx sudo systemctl restart nginx.service

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment