Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 beginning 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?


2 Answers

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>
like image 57
Lekensteyn Avatar answered Sep 07 '25 18:09

Lekensteyn


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.

like image 44
Meglio Avatar answered Sep 07 '25 16:09

Meglio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!