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.

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

sudo -s
apt update && apt upgrade -y
apt install nginx-module-geoip geoip-database libgeoip1 -y

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

vhost: gateway.conf or nextcloud.conf
it depends on whether NGINX is acting as a reverse proxy or as a default webserver

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 our Nextcloud, except germans and LAN users who are explicitly allowed.

load_module "modules/";
user www-data;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/;
events {
worker_connections 1024;
multi_accept on; use epoll;
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
geo $vlan {
default 0; 1; #adjust to your private LAN 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 proper vhost file

  • EITHER for NGINX acting as a reverse proxy webserver using a gateway configuration:
vi /etc/nginx/conf.d/gateway.conf
server {
listen 443 ssl http2 default_server;
include /etc/nginx/ssl.conf;
include /etc/nginx/header.conf;
include /etc/nginx/ipblocker;
  • OR for NGINX acting as a default webserver
vi /etc/nginx/conf.d/nextcloud.conf
server {
listen 443 ssl http2 default_server;
root /var/www/nextcloud/;
include /etc/nginx/ipblocker;

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 13 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.