NGINX Restrict Access to Directory and Subdirectories

Sometimes you may need to limit access to certain folders and subfolders on your website, due to their sensitive nature of information. NGINX allows you to easily restrict access to directory and subdirectories using Deny and Allow directives.


NGINX Restrict Access to Directory and Subdirectories

Here are the steps to restrict access to directory and subdirectories in NGINX. Deny directive allows you to block access to URL, directories and folders from one or more IP addresses. On the other hand, Allow directive allows you to permit access to URL, directories and folders from one or more IP addresses.


1. Open NGINX configuration file

Open terminal and run the following command to open NGINX configuration file.

$ sudo vi /etc/nginx/nginx.conf

If you have configured separate virtual hosts for your website (e.g www.example.com), such as /etc/nginx/sites-enabled/example.conf then open its configuration with the following command

$ sudo vi /etc/nginx/sites-enabled/example.conf

Also read : How to Restrict Access to URL in NGINX


2. Restrict Access to URL

Let us say you want to limit access to /product directory by IP 45.34.21.10.

In that case add the Deny directive

Deny 45.34.21.10

in the location block for /product, in your NGINX server configuration.

location /product {
   ...
   deny 45.34.21.10;
   ...
}

If you want to restrict access to folders and subfolders by all IPs except one known IP 45.34.21.10, then add the following Deny and Allow statements as shown.

location /product {
   ...
   Allow 45.34.21.10;
   Deny All;
   ...
}

The allow statement will allow access to specified IP and deny statement will limit access to all other IPs.

Also read : How to Configure Log Rotation in NGINX

If you want to limit access to directory for multiple IPs add separate Deny statements, one for each IP as shown.

location /product {
   ...
   Deny 45.34.21.10;
   Deny 54.23.10.13;
   ...
}

If you want to limit access to directory for an IP range such as 45.23.10.0-45.23.10.255 then specify IP range using CIDR notation.

location /product {
   ...
   Deny 45.34.21.0/24;
   ...
}

Also Read : How to Fix Too Many Workers Error in NGINX


3. Restart NGINX Server

Finally, run the following command to check syntax of your updated config file.

$ sudo nginx -t

If there are no errors, run the following command to restart NGINX server.

$ sudo service nginx reload #debian/ubuntu
$ systemctl restart nginx #redhat/centos

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it today!

mm

About Ubiq

Ubiq is a powerful dashboard & reporting platform for small & medium businesses. Build dashboards, charts & reports for your business in minutes. Get insights from data quickly. Try it for free today!