How to Deny Access to File in NGINX


how to deny access to file in nginx

Sometimes, you might need to restrict access to specific files on your website, because they have sensitive or confidential information. Here’s how to deny access to file in NGINX.

 

How to Deny Access to File in NGINX

Here are the steps to deny access to file in NGINX. We will use the deny directive to deny access to file. When users try to access such a file, they will get “403:Access forbidden” response.

 

1. Open NGINX config file

Open NGINX config file in a text editor. You will find it in /etc/nginx/nginx.conf. You can update the location as per your requirement.


$ sudo vim /etc/nginx/nginx.conf

 

2. Block access to files

Let’s say you want to block access to a specific .php file (sensitive.php). Then add the following location block for that file

 

Block everyone


location = /sensitive.php {
 deny all;
}

 

The above location block will do an exact match for “sensitive.php” string in URL. If you want a regular expression-based match then update the location block as shown

 


location ^~ /sensitive.php {
 deny all;
}

 

Block specific IP

If you only want to block a specific IP (10.10.10.10) then update the location block as shown


location = /sensitive.php {
 deny 10.10.10.10;
}

 

Block multiple IPs

If you only want to block a multiple IPs (10.10.10.10 and 11.11.11.11) then you can use multiple deny directives one below the other.


location = /sensitive.php {
 deny 10.10.10.10;
 deny 11.11.11.11;
}

 

Allow only specific IP

If you only want to allow a specific IP (10.10.10.10) then update the location block as shown. In this case, we use deny directive after allow directive.


location = /sensitive.php {
 allow 10.10.10.10;
 deny all;
}

 

Block IP range

If you only want to block a specific range of IPs (43.248.64.0-43.248.64.255) then you can use IP ranges using CIDR notation as shown. Update the location block as


location = /sensitive.php {
 deny 43.248.64.0/20;
}

 

3. Reload NGINX server

Reload NGINX web server to apply changes.


$ sudo service nginx reload

 

That’s it! Now when users to try to access your file, they will get a “403: Access Forbidden” response from your server.

 

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!