Match / Deny access to all subdirectories using apache2 server configuration Match / Deny access to all subdirectories using apache2 server configuration apache apache

Match / Deny access to all subdirectories using apache2 server configuration


in the end, the solution turns out to be pretty simple:

<Directory /var/www/*/>    Allow from None    Order allow,deny</Directory>

Note the trailing slash / after the directory pattern, which will make it match only directories, not files!

This works exactly like we would expect from the <Directory>-directive - in that it denies access only to the direct subdirectories of /var/www/.Specified subdirectories (anywhere in the tree) can still manually be re-enabled with <Directory> directives.

This is in contrast to <DirectoryMatch> which will
- also match all files & directories in the tree and
- override all <Files> or <Directory> directives for any item in the tree.


This did it for me.

<DirectoryMatch "^/var/www/(.+)/"> # don't put $ at the endOrder Allow,DenyDeny From All</DirectoryMatch>


EDIT

For not denying sub-subdirectories (comment below), add this DirectoryMatch below the one above in your configuration file:

<DirectoryMatch "^/var/www/(.+?)/(.+)/"> # again no $, see commentOrder Deny,AllowAllow From All</DirectoryMatch>


Use this:

<Directory /var/www/public>    allow from all</Directory><DirectoryMatch "^/var/www/public/(.+)/">   deny from all</DirectoryMatch>

You might want to add Options etc.

The trick is how the directives are merged.