Posts Tagged server config
Prevent file viewing with htaccess
Posted by Wil in htaccess tutorials on February 12, 2010
If you have a directory which contains passwords or files that you don’t want anybody to be able to view or to download, you might add the following to your .htaccess file :
- If you want to prevent people from viewing all the files :
<Files *>
Order allow,deny
Deny from All
</Files>
- If you don’t want anybody to be able to view only the files with a specific extension :
<Files ~ “\.(sql)$”>
Order allow,deny
Deny from All
</Files>
In that example, all files except those with sql extension will be available for web visitors.
- if you want to prevent people from viewing files with more than one extension :
<Files ~ “\.(tpl|sql|other-extension…)$”>
Order allow,deny
Deny from All
</Files>
In that case, all files except those with tpl, or sql or other-extension will be accessible.
Another example : if you want to prevent .htaccess and .htpasswd files from viewing by web clients, you can place the following :
<Files ~ “^\.ht”>
Order allow,deny
Deny from All
</Files>
To replace a wild-card string, you can use ‘?’ to match any single character, and ‘*’ to match any sequences of characters.
If you use extended regular expressions, don’t forget to add the ~ character.
<Files ~ “\.(gif|bmp|jpe?g)$”>
Order allow,deny
Deny from All
</Files>
- If you want to be more selective and forbid a single file within a particular directory, place the following in your .htaccess file :
<Files config.php>
Order allow,deny
Deny from All
</Files>
The <Files> directive allows you to control access to your own files. You can include various <Files> directives in your htaccess file.
Remember that <Files> directive applies to subdirectories, so it will also protect files in subdirectories, unless specifically overridden.
In Apache 1.3 and later, another directive provides for access control by filename : <FilesMatch>. The <FilesMatch> directive accepts a regular expression.
An example, using the <FilesMatch> directive (preferred with Apache 1.3 and later) :
<FilesMatch “\.(gif|bmp|jpe?g)$”>
Order allow,deny
Deny from All
</FilesMatch>