X

Block Countries With Nginx and GeoIP

You can use nginx to either allow or deny certain countries from accessing your site using the GeoIP database which maps IP addresses to the origin country.

Nginx GeoIP Requirements

Nginx Installation – Nginx must already be installed on your server if it is not yet. Please see How to Install Nginx

Nginx must also be compiled with –with-http_geoip_module

To make sure type the following

nginx -V 2>&1|grep --color=always with-http_geoip_module

You should see the returned output contain with-http_geoip_module

If it does not, you will need to change to the source direct copy the entire configuration line and append –with-http_geoip_module to reconfigure

./configure --user=nginx --group=nginx --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --with-http_gzip_static_module --with-http_stub_status_module --with-http_ssl_module --with-pcre --with-file-aio --with-http_realip_module --without-http_scgi_module --without-http_uwsgi_module --with-http_realip_module --with-http_geoip_module

Then

make && make install

Install the GeoIP Database

Create a new directory for the GeoIP database to go:

mkdir /usr/share/geoip

Change to that directory:

cd /usr/share/geoip

Get the latest GeoIP database, this is the free ‘lite’ version. MaxMind also offers paid versions as well.

wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz

Gunzip the database:

gunzip GeoIP.dat.gz

Configure Nginx

Nginx needs a global configuration and then to be told in each server block to restrict IP access.

nano /etc/nginx/nginx.conf

You will want to insert the following in to the http{} block

geoip_country /usr/share/geoip/GeoIP.dat;
 map $geoip_country_code $allow_country {
 default yes;
 EG no;
 FR no;
 FI no;
}

Each country code you want to block would be indicated above. This wont create the actual block it will just create the map. Next you will want to edit the server{} block and add the following

if ($allow_country = no) {
 return 403;
}

You will then save the file and restart nginx

service nginx restart

Now any countries you have set to ‘no’ will receive a 403 forbidden page.  This could be switched to only allow certain countries, by setting the default to no and entering each country with a yes next to it that you wanted to allow.

LinuxAdmin.io
5 1 vote
Article Rating
LinuxAdmin.io:
Related Post