Country Blocking with nginx GeoIP on Ubuntu/Debian
On Ubuntu/Debian, install nginx geoip module with
1 |
apt install geoip-database libgeoip1 libnginx-mod-http-geoip -y |
Now edit nginx.conf
1 |
vi /etc/nginx/nginx.conf |
Find
1 |
http { |
Add below
1 2 3 4 5 6 7 |
geoip_country /usr/share/GeoIP/GeoIP.dat; map $geoip_country_code $my_country_blocker { default no; US yes; AU yes; CA yes; } |
You can add 2 letter country code and set ye/no as required.
To implement GeoIP blocking for a web site, you need to edit server entry for the web site. In this cause, i will use the default web site.
1 |
vi /etc/nginx/sites-enabled/default |
Find
1 |
server { |
Add blow
1 2 3 |
if ($my_country_blocker = no) { return 444; } |
This will block access to the web site from any country that is not listed in nginx.conf
You need to restart nginx web server
1 |
systemctl restart nginx |
If you need to redirect blocked users to another site, use
1 2 3 |
if ($my_country_blocker = no) { rewrite ^ https://google.com break; } |
This will redirect the visitor to google if their country is not US, AU or CA.
See Nginx