How to Deny Access to .htaccess in NGINX


deny access to .htaccess in nginx

.htaccess is a useful hidden file that allows you to change Apache server config file without actually accessing its config file. However, since it is such an important file, it is vulnerable to malicious attacks. So it is advisable to deny access to .htaccess via your web server, so it doesn’t get served accidentally. Let us take a look at how to deny access to .htaccess in NGINX.

 

How to Deny Access to .htaccess in NGINX

Here are the steps to deny access to .htaccess in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. Typically it is located at /etc/nginx/nginx.conf


$ sudo vim /etc/nginx/nginx.conf

 

2. Deny access to .htaccess

Add the following block of code to deny access to .htaccess file.


location ~ /\.htaccess$ {
 deny all;
 error_page 403 =404 / ;
}

 

If you want to deny access to only specific IPs,


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

 

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


location ~ /\.htaccess$ {
 deny 54.34.21.0/24;
 error_page 403 =404 / ;
}

 

If you want to deny access to all but a few specific IPs, use the allow directive,


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

 

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!