开发者

Apache configuration: Regex to disable access to files/directories beginning with a dot

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 beginni开发者_如何学Cng with DOT only if they are directly in the Document root.

<Files ~ "^\.|\/\.">
    Order allow,deny
    Deny from all
</Files>

With this,

http://my_server.com/.svn/entries   --> Permission denied
http://my_server.com/abcd/.svn/entries  --> Accessible, should be disabled

Whats the proper regex to achieve this?


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>


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).


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜