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.
Steps
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
192.168.1.1/32 0;
# My Office IP
192.168.1.2/32 0;
}
Create a configuration for the website you wish to filter for.
sudo vim /etc/nginx/sites-enabled/my.website.com;
include /etc/nginx/whitelisted_ips.conf
server {
listen 80;
# order of specificity is important if allowing aliases
server_name my.website.com website.com;
access_log /var/log/nginx/my.website.com-access.log;
location / {
if ($bad_user) {
rewrite ^ http://my.other.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
Finally, make sure 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.
References
- StackOverflow - Nginx - Different proxy pass based on IP ranges
- Serverfault - Nginx - How to redirect users with certain IP to special page
First published: 16th August 2018