.htaccess file allows you to modify Apache server config without accessing configuration files. You can even use it to control access to URLs, directories and files. Here’s how to deny access to all files using .htaccess.
How to Deny Access to All Files Using .htaccess
Here are the steps to deny access to all files using .htaccess. Before you proceed, please ensure that you have enabled mod_rewrite (.htaccess) in your Apache web server. Here are the steps to do it in:
Place your .htaccess file in the root document folder of your website (/var/www/html) and add the following rules.
1. Open .htaccess file
Open .htaccess file in a text editor.
$ sudo vim /var/www/html/.htaccess
2. Deny access to files
Let’s say you want to deny access to all php files on your website. Then add the following block to your .htaccess file.
<Files *.php> Order Deny,Allow Deny from all </Files>
If you are using Apache 2.4+, then use
<Files *.php> Require all denied </Files>
The above code will deny access to all php files on your website.
If you want to deny access to all php files in a specific folder (e.g /include/) then place a blank .htaccess file in that folder and add the above block of code in it.
If you want to deny access to all except a few specific IP addresses, then use the allow block to allow access
<Files *.php> Order Deny,Allow Deny from all Allow from 127.0.0.1 Allow from 188.8.131.52 Allow from 184.108.40.206 </Files>
You can also allow access from IP ranges (e.g 220.127.116.11 – 18.104.22.168) using CIDR notation.
<Files *.php> Order Deny,Allow Deny from all Allow from 22.214.171.124/24 </Files>
If you want to deny access to multiple file types, use FilesMatch directive
<FilesMatch "\.(htaccess|htpasswd|ini|php|conf)$"> Order Deny,Allow Deny from all </Files>
3. Restart Apache Web Server
Restart Apache web server to apply changes.
$ sudo /etc/init.d/apache2 start [Debian or Ubuntu] # sudo apachectl restart [RHEL, CentOS or Fedora]