How to Restrict Access by File Type in .htaccess


restrict access by file type .htaccess

Apache allows you to do access control by file types and extensions. You can set up access conditions in .htaccess file, without modifying server config file. Let us take a look at how to restrict access by file type in .htaccess.

 

How to Restrict Access by File Type in .htaccess

Here’s how to restrict access by file type in .htaccess. Before proceeding, please ensure that you have enabled mod_rewrite (.htaccess) in your Apache web server. Here are the steps to do it:

Place your .htaccess file in the root document folder of your website (/var/www/html) and add the following rules, depending on your use case.

 

1. Open .htaccess file

Open .htaccess file in a text editor.


$ sudo vim /var/www/html/.htaccess

 

2. Restrict Access by File Type

Let’s say you want to restrict access to .php files on your website. You can do that with the help of FilesMatch directive.


<FilesMatch "\.php$">
Order Allow,Deny
Deny from all
</FilesMatch>

The above code will match all php files and restrict access to them.

For Apache 2.4+


<FilesMatch "\.php$">
Require All Denied
</FilesMatch>

If you want to restrict access to multiple file types (.php, .ini, .conf, .log), then use the ‘|’ operator to combine them into a single expression


<FilesMatch "\.(php|ini|conf|log)$">
Order Allow,Deny
Deny from all
</FilesMatch>

 

For Apache 2.4+


<FilesMatch "\.(php|ini|conf|log)$">
Require All Denied
</FilesMatch>

 

You can also deny access to specific IPs (e.g 54.34.21.11)


<FilesMatch "\.(php|ini|conf|log)$">
Require All Granted
Require not ip 54.34.21.11
</FilesMatch>

 

You can also deny access to specific IP ranges (54.34.21.0 – 54.34.21.255) using CIDR notation.


<FilesMatch "\.(php|ini|conf|log)$">
Require All Granted
Require not ip 54.34.21.11
</FilesMatch>

 

 

The above codes will restrict to all files in your website, that match your required condition.

However, if you only want to restrict access to files in a specific folder (e.g /admin/) then place a blank .htaccess file in it with the above code. In this case, the rules present in your .htaccess file will be applied only to the files present in its folder.

 

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]

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!