How to Deny Access to Directory in NGINX


deny access to directory nginx

NGINX is a powerful web server with powerful access control features. It allows you to block access to URLs, files and even directories. Here’s how to deny access to directory in NGINX.

 

How to Deny Access to Directory in NGINX

Here’s how to deny access to directory in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. It is generally located at /etc/nginx/nginx.conf. If not, then please update the path to your NGINX config file in the command below.


$ sudo vim /etc/nginx/nginx.conf

 

2. Deny Access to Directory

Let’s say you want to deny access to /include/ then add the following block to nginx.conf


location ~ /include {
 deny all;
 return 403;
}

In the above case, users who try to access /include/ folder will get a “403 : Access Forbidden” error. If you want to show a “404: Page not found” error, then modify the return code to 404


location ~ /include {
 deny all;
 return 404;
}

 

If you want to deny access to multiple directories (dir1, dir2, dir3), then you can use the ‘|’ operator to combine them


location ~ /(dir1|dir2|dir3) {
 deny all;
 return 404;
}

 

If you want to deny access to only a few specific IPs, you can use multiple deny statements


location ~ /(dir1|dir2|dir3)$ {
 deny 52.34.10.13;
 deny 51.44.211.13;
 return 404;
}

 

If you want to deny access to range of IP addresses (53.14.1.0-53.14.1.255), then use CIDR notation.


location ~ /(dir1|dir2|dir3)$ {
 deny 53.14.1.0/24;
 return 404;
}

 

If you want to deny access to all except a few specific IPs, use the allow directive to specify the IP that you want to allow access


location ~ /(dir1|dir2|dir3)$ {
 deny all;
 allow 51.4.1.13;
 allow 52.1.11.1;
 return 404;
}

 

You can also use the CIDR notation in allow directive to specify a range of IPs


location ~ /(dir1|dir2|dir3)$ {
 deny all;
 allow 52.24.11.0/24;
 return 404;
}

 

3. Reload NGINX Server

Reload NGINX server to apply changes.

$ sudo service nginx reload

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!