How to Restrict Access to Directory & Subdirectories in NGINX


nginx-restrict access directory subdirectories

Sometimes, you may need to restrict to certain parts of your website, specific URLs, directories and subdirectories that contain sensitive information. You can easily do it in NGINX server. Let us take a look at how to restrict Access to directory & subdirectories in NGINX.

 

How to Restrict Access to Directory & Subdirectories in NGINX

Here are the steps to restrict access to directory and subdirectories in NGINX.

 

Let’s say you need to limit access to your directory /wp-admin to only an internal IP (e.g 192.168.1.1) and deny access to everyone else.

 

1. Open NGINX Config file

Open a terminal session or SSH into Linux system. Run the following command to open your NGINX config file in a text editor


$ sudo vim /etc/nginx/nginx.conf

 

2. Update NGINX config file

Add the following location block in it


location ~ /wp-admin {
 allow 192.168.1.1;
 deny all;
}

The above code will deny access to /wp-admin for all except the IP you have mentioned, 192.168.1.1. If anyone else tries to access this folder, they will get a “403 Access Forbidden” message.

If you don’t want anyone to be able to access it, simply remove the allow directive

 


location ~ /wp-admin {
 deny all;
}

 

Restrict Access to Multiple directories

If you want to deny access to multiple directories and sub directories (dir1, dir2, etc) you can combine them with the ‘|’ operator as shown


location ~ /(dir1|dir2|dir3) {
 allow 192.168.1.1;
 deny all;
}

 

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!