More privacy using geoip

nginx using geoip


Many users asked for the NGINX geoip configuration i made earlier. Although e.g. VPN or TOR could bypass geoip blocking i decided to post a new guide. So following this guide you will be able to secure your Nextcloud server a bit more by using geoip in few steps only.

sudo -s

Add a new software repository

cd /etc/apt/sources.list.d
echo "deb [arch=amd64] https://packages.sury.org/nginx-mainline/ $(lsb_release -cs) main" | tee nginx.list
wget -q https://packages.sury.org/php/apt.gpg -O- | apt-key add -

Update your server and install the necessary modules for NGINX by issuing

apt update && apt upgrade -y
apt install nginx nginx-extras -y

Modify the current nginx.conf and the relevant vhost file to participate from geoip filtering

vi /etc/nginx/nginx.conf

Add and amend all the red ones. We set examplarily “default 0” and allow in particular  “DE” that implicits nobody may connect to your Nextcloud, except germans and LAN users who are explicitly allowed.

load_module "modules/ngx_http_geoip_module.so";
user www-data;
worker_processes auto;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
multi_accept on; use epoll;
}
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
geo $vlan {
default 0;
192.168.2.0/24 1; #adjust to your private LAN
127.0.0.1 1;
}
... }

Create a new ipblocker file

touch /etc/nginx/ipblocker

and paste the following rows:

set $geoipblock 0;
if ($geoip_country_code !~ (DE)) {set $geoipblock 1;}
if ($vlan = 1){set $geoipblock 0;}
if ($geoipblock = 1){return 410;}

You may add further countries ‘|’ separated: e.g.  (DE|AT|IT) – find the entire ISO 3166 Country Codes list here

Now modify the nextcloud.conf file

vi /etc/nginx/conf.d/nextcloud.conf
server {
server_name your.dedyn.io;
listen 80 default_server;
listen [::]:80 default_server;
include /etc/nginx/ipblocker;
...
server {
server_name your.dedyn.io;
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server; include /etc/nginx/ipblocker; root /var/www/nextcloud/;
...

Verify your NGINX  configuration

nginx -t

and if no errors appear restart your webserver by

service nginx restart

Your webserver will now respond with an error code 410

to all client requests coming from outside germany or your defined countries.


Carsten Rieger

Carsten Rieger is a senior system engineer in full-time and also working as an IT freelancer. He is working with linux environments for more than 15 years, an Open Source enthusiast and highly motivated on linux installation and troubleshooting. Mostly working with Debian/Ubuntu Linux, Nginx and Apache web server, MariaDB/MySQL/PostgreSQL, PHP, Cloud infrastructure (e.g. Nextcloud) and other open source projects (e.g. Roundcube) and in voluntary work for the Dr. Michael & Angela Jacobi Stiftung for more than 7 years.