Programster's Blog

Tutorials focusing on Linux, programming, and open source

NGINX - Redirecting Non Whitelisted IPs

In this tutorial, we will be using the geo module for NGINX to allow specific IPs through, and redirect all others to a page letting them know that access has been restricted and that they don't have access. This was done using Ubuntu 16.04, but should be similar for other distros.


The first thing we need to do is install NGINX (luckily this comes with the geo module).

sudo apt install nginx -y

Because I will be whitelisting the IPs for a range of websites, I am creating a single configuration file that has the IPs in it that all the site configs will include.

sudo vim /etc/nginx/whitelisted_ips.conf
geo $bad_user {
    default 1;

    # My Home IP 0;

    # My Office IP 0;

Create a configuration for the website you wish to filter for.

sudo vim /etc/nginx/sites-enabled/;
include /etc/nginx/whitelisted_ips.conf

server {
    listen 80;

    # order of specificity is important if allowing aliases

    access_log /var/log/nginx/;

    location / {
        if ($bad_user) {
            rewrite ^;

        # include the default proxy_params conf in order 
        # to set headers for proxying.
        include /etc/nginx/proxy_params;

        # Send the user off to the backend server. 
        # They will only get here if they are whitelisted.

Now test your configurations by running:

sudo nginx -t

If it gives you the all clear, have nginx use the configuration with:

sudo nginx -s reload

Finally, make sure the backend webserver ( in this case) is not accessible by the user just going to the IP, or if the user was to falsify their own DNS to go to that IP. The best way to do this is probably to have it's firewall only accept connections from the proxy.