NGINX IP Whitelist by Directory

Overview

In this example, I have a shared hosting environment where I want to limit access to certain NGINX web directories by IP whitelist. I am going to create an admin IP list, and a customer1 IP list. Then I will allow the admin IP list to access both admin and customer1 directories, but only allow customer1 to access customer1 directory.

Configuration

Setup

Create directories inside the “app” website

mkdir /var/www/app/admin
chown www-data:www-data /var/www/app/admin
mkdir /var/www/app/customer1
chown www-data:www-data /var/www/app/admin

Create whitelists

Create whitelist called admin-ips

nano /etc/nginx/includes/admin-ips
allow 1.2.3.4;

Create whitelist called customer1-ips

nano /etc/nginx/includes/customer1-ips
allow 4.3.2.1;

Apply whitelists to NGINX directories

Edit NGINX config for website called “app”

nano /etc/nginx/sites-enabled/app

In the server Listen 80 section, add this to the end

location ^~ /admin/ {
    include /etc/nginx/includes/admin-ips;
    deny all;
}


location ^~ /customer1/ {
    root /var/www/app;
    include /etc/nginx/includes/admin-ips;
    include /etc/nginx/includes/customer1-ips;
    deny all;
}

In the server Listen 443 section, add this to the end

location ^~ /admin/ {
    include /etc/nginx/includes/admin-ips;
    deny all;
}

location ^~ /customer1/ {
    root /var/www/app;
    include /etc/nginx/includes/admin-ips;
    include /etc/nginx/includes/customer1-ips;
    deny all;
}

Reload NGINX for changes to take effect

service nginx reload

Share on Facebook