Last Updated on July 22, 2021 by Amit
What is files directive and how to use it
Files directive is part of Apache core module . You can use this directive in an htaccess or server configuration file to apply other directive to one specific file or files inside files directive.
This directive works like a condition . You can use RewriteRule or Redirect directives inside files block so that the rule can apply to one specific file.
Code examples of files directive
You can use RewriteRule inside files directive something like the following :
<files "demo.php"> RewriteEngine on RewriteRule .+ - [F,L] </files>
The rule above rewrites a request to 403 forbidden page . As you can we have used a catch-all pattern in the rule but this will only apply to a specific file demo.php .
You can deny access to a specific file use deny directive something like the following :
<files "demo.php"> Deny from all </files>
The code above denies access to a specific file named demo.php .
If you want to use a regular expression based match in files then you need to use a ~ character.
<files ~ ".+\.php$"> deny from all </files>
The code above searches for all PHP files a denies the access.
How to use FilesMatch directive in htaccess
FilesMatch directive is same as Files except for one thing. FilesMatch uses a regular expression based pattern instead of static one. You can also use regex with files directive with a ~ char but in FilesMatch you can use a pure regex based pattern.
<filesMatch ".+\.html$"> ReditectMatch 404 .html </FilesMatch>
The code above redirects all html files to 404 not-found error.