How to Deny Access to File Extension in NGINX


deny access to file extension in nginx

When you run a website, it is useful to block access to certain files, based on their extension. It makes your site secure and blocks malicious attacks. NGINX web server allows you to deny access to file extensions. Let us look at how to deny access to file extension in NGINX.

 

How to Deny Access to File Extension in NGINX

Here’s how to deny access to file extension in NGINX.

 

1. Open NGINX server config

Open NGINX server config file in a text editor. You will find it at /etc/nginx/nginx.conf. If not, please update the path below according to your requirement.


$ sudo vim /etc/nginx/nginx.conf

 

2. Deny Access to File Extension

Let’s say you want to deny access to log files (.log), then add a location block as shown below.


location ~\.(log)$ {
 deny all;
 error_page 403 =404 / ;
}

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


location ~\.(log)$ {
 deny 54.34.21.13;
 deny 56.44.11.13;
 error_page 403 =404 / ;
}

 

If you want to deny access to range of IP addresses (54.34.21.0-54.34.21.255, then use CIDR notation.


location ~\.(log)$ {
 deny 54.34.21.0/24;
 error_page 403 =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 ~\.(log)$ {
 deny all;
 allow 54.34.21.13;
 allow 54.21.11.10;
 error_page 403 =404 / ;
}

 

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


location ~\.(log)$ {
 deny all;
 allow 54.34.21.0/24;
 error_page 403 =404 / ;
}

 

If you want to deny access to multiple file extensions (e.g .ini, .log, .php, .conf), you can combine them using the ‘|’ operator,


location ~\.(ini|log|conf|php)$ {
 deny all;
 error_page 403 =404 / ;
}

 

3. Reload NGINX web 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!