Wednesday, 24 January 2018

How to redirect non Whitelisted IPs in NGINX

We are 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 linux distros.

Steps:

You have to install NGINX first.

sudo apt install nginx -y

Now create a file for single configuaration 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
    192.168.1.1/22 0;

    # My Workspace IP
    192.168.1.2/22 0;
}

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

sudo vim /etc/nginx/sites-enabled/mywebsite.com;

include /etc/nginx/whitelisted-ips.conf

server {
    listen 80;

    # order of specify is important if allowing aliases
    server_name mywebsite.com;

    access_log /var/log/nginx/mywebsite.com-access.log;

    location / {
        if ($bad_user) {
            rewrite ^ http://myother.site.com/access-restricted-landing-page;
        }

        # 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.
        proxy_pass http://xxx.xxx.xxx.xxx;
    }
}

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

Now access the backend webserver (http://xxx.xxx.xxx.xxx 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.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts