How to Restrict Access to File Type in NGINX


restrict access to file type nginx

NGINX is a powerful web server that allows you to do file access control in various ways, by applying different conditions. Let us take a look at how to restrict access to file type in NGINX.

 

How to Restrict Access to File Type in NGINX

Here’s how to restrict access to file type in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. Typically, it is located at /etc/nginx/nginx.conf. If you have set it up at a different location, then update its path in the command below.


$ sudo vim /etc/nginx/nginx.conf

 

2. Restrict Access to File Type

Let us say you want to restrict access to .php files, all over your website, then add the following block of code in your config file


location ~\.php$ {
 deny all;
}

In the above case, when users try to access php file on your website, they will get a “403: Access Forbidden” error. If you want to return a “404: Page not found” error, you can simply return a 404 response code.


location ~\.php$ {
 deny all;
 return 404;
}

 

If you want to restrict access to all php files in only a specific directory (e.g /admin/), modify your location block as shown


location ~ /admin/\.php$ {
 deny all;
}

 

If you want to restrict access only to a few IPs, you can specify them in deny directive


location ~\.php$ {
 deny 54.34.21.13;
 deny 56.44.11.13;
}

 

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


location ~\.php$ {
 deny 54.34.21.0/24;
}

 

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 ~\.php$ {
 deny all;
 allow 54.34.21.13;
 allow 54.21.11.10;
}

 

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


location ~\.php$ {
 deny all;
 allow 54.34.21.0/24;
}

 

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;
}

 

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!