I want to disable access to any file OR directory, whose name begins with a DOT. I came up with the following, but it disables access to files/directories beginning with DOT onl
RewriteRule (^\.|/\.) - [F]
This will deny from viewing any files or directories beginning with dot. It affects any level in the paths tree.
[F] modifier at the end says to forbid access (no need for L modifier to say that it is Last rule to apply, it is implied by default).
The regular expression has two parts (any of them allowed to match, not required to be both):
(part1|part2)
The first part matches anything that starts from dot (for the case when you use it in per-directory .htaccess file and there will be no slash at the start of string we are matching on):
^\.
For example, this will work for .test
, .git/HEAD
but will not work for /.git
, path/.hidden
.
The second part matches anything that contains slash followed by dot. This is useful if you have this rule in VirtualHost or in side-wide Apache configuration, in which a case string we match may begin with slash.
This rule will match: /.git
, some/.hidden
This rule will not match: .git
, .hidden
When we combine these both rules, it seems that we cover all possible cases.
This works perfectly for me (Apache 2.4):
<LocationMatch "\/\.">
Require all denied
</LocationMatch>
Denies any URL that contains a component beginning with a dot (file or directory).
You code does not work because <Files>
only applies to the basename of the requested document. That is, the part after the last slash. (source: http://httpd.apache.org/docs/current/mod/core.html#files)
Apache blocks .htaccess
files in a default installation (better: all files starting with .ht
). If you looked closely at the configuration files, you would see something like this:
<FilesMatch "^\.ht">
Order allow,deny
Deny from all
</FilesMatch>
So to hide all files starting with a dot, you would use:
<FilesMatch "^\.">
Order allow,deny
Deny from all
</FilesMatch>
In order to make it work for directories starting with a dot, use the following (tested) code:
<DirectoryMatch "^\.|\/\.">
Order allow,deny
Deny from all
</DirectoryMatch>
With rewrite mod:
RewriteEngine on
RewriteCond %{THE_REQUEST} ^.*/\.
RewriteRule ^(.*)$ - [R=404]
Every file or dir who begin with a dot will be redirected to 404.
/myDir/.svn => 404
/.gitignore => 404
/dir1/dir2/dir3/..../.toHide => 404