m2.nz/content/posts/nginx_geo_block.md

40 lines
1.2 KiB
Markdown
Raw Permalink Normal View History

2024-04-06 22:59:01 +00:00
---
2024-04-06 23:11:11 +00:00
title: "GeoIP blocking countries using Nginx"
2024-04-06 23:04:42 +00:00
tags: ["nginx", "geoip", "spam", "geo block"]
date: "2024-04-06"
2024-04-06 22:59:01 +00:00
---
Quick and easy way to block entire countries using simple nginx rules.
2024-04-06 23:04:42 +00:00
Note this is for Ubuntu/Nginx but may work on other systems.
2024-04-06 22:59:01 +00:00
2024-04-06 23:04:42 +00:00
Install required packages & add to nginx config.
The GeoIP DB will be under /usr/shared/GeoIP/GeoIPv6.dat (Or GeoIP.dat for v4 only):
2024-04-06 22:59:01 +00:00
```shell
2024-09-21 22:12:39 +00:00
sudo apt install -y libnginx-mod-http-geoip geoip-database
2024-04-06 23:10:31 +00:00
echo 'geoip_country /usr/share/GeoIP/GeoIPv6.dat;' > /etc/nginx/conf.d/geoip.conf
2024-04-06 22:59:01 +00:00
```
Add this block under the main "http" block in nginx.conf:
```shell
# /etc/nginx/nginx.conf
map $geoip_country_code $allowed_country {
default yes;
BD no; # Country code to block - Can list mulitple
}
```
2024-04-06 23:04:42 +00:00
Then we need to add a simple check in our site vhost inside the `server {` block, but before the `location /` block:
2024-04-06 22:59:01 +00:00
```shell
2024-09-21 22:12:39 +00:00
# /etc/nginx/sites-enabled/site.conf or /etc/nginx/conf.d/site.conf
2024-04-06 22:59:01 +00:00
if ($allowed_country = no) {
return 403;
}
```
Quick reload and boom! Done!
```shell
2024-09-21 22:12:39 +00:00
sudo systemctl reload nginx
2024-04-06 22:59:01 +00:00
```
Based off an older gist found on [Github here](https://gist.github.com/dunderrrrrr/8d3fced1f73de2d70ede38f39c88d215)