In this post I’ll try to explain how NGINX GeoIP module can be used to restrict access to your web-portal/website only to a specific geographical region.
Begin by verifying NGINX GeoIP module is installed on the server which can be done via
nginx -V
if you can see –with-http_geoip_module in the output you are ready to use the GeoIP database with NGINX but if not you can install it on the server using the following command (for ubuntu)
apt-get install geoip-database libgeoip1
this will install GeoIP database usually at the following location /usr/share/GeoIP/GeoIP.dat.
Go ahead and re-configure your nginx.conf file, usually located inside /etc/nginx/ folder based on your installation, by adding following instructions inside http {} block
geoip_country /usr/share/GeoIP/GeoIP.dat; map $geoip_country_code $allowed_country { default no; US yes; }
this sets $allowed_country to yes if your webportal/website is being accessed from USA. For all other locations trying to access your server the default value will be used which is no.
Now you can configure your virtual server configurations by adding the following instructions inside server {} block.
if ($allowed_country = no) { return 403; }
and this will block all the traffic, except for USA, to your virtual server by returning the 403 status code.
As the blocking is done based on the information of IP addresses available inside the GeoIP database it’d make sense to update the database at regular intervals which can be easily done using a cron job. You can use the following script (geoIP-update.sh) to make it happen
#!/bin/bash cd /usr/share/GeoIP echo =============== updating database=============== wget "http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz" -P /YOUR/PATH/HERE || { echo 'Cannot download database, exiting.' ; exit 1; } gunzip /YOUR/PATH/HERE/GeoIP.dat.gz mv -f /YOUR/PATH/HERE/GeoIP.dat /usr/share/GeoIP/
and schedule a job via
crontab -e
by adding the following
* 12 * * 3 /usr/share/GeoIP/geoIP-update.sh
Make sure to modify * 12 * * 3 according to your update interval requirements.
This article was first published on the Knoldus blog.
No comments:
Post a Comment