10.7. Blocking access to files

There is one last aspect of access control we must consider. We have stopped certain files being listed in indexes in Section 6.3 but we warned that this did not stop the files being downloaded if the client could guess the name. This section will demonstrate how to block downloads of files matching certain expressions in the same way as the IndexIgnore command stops files matching those patterns being listed.

We can restrict certain commands to files that match regular expressions with the <FilesMatch> ... </FilesMatch> directive. We can put a simple denial of all access in this block.

In an ideal world, IndexIgnore and <FilesMatch> would accept the same syntax for describing their files. Unfortunately they don't, and this is a serious flaw in the Apache Software Foundation's way of handling their modules. IndexIgnore uses shell-style wildcards, formally known as globbing, and <FilesMatch> uses sed-style regular expressions.

Our current example configuration file has the line

IndexIgnore  "#*#"  "*~"  "configuration"
and the equivalent <FilesMatch> regular expression is
(^#.*#$|.*~$|^configuration$)

An apropriate configuration would be:

<FilesMatch (^#.*#$|.*~$|^\..*|^configuration$)>
  Order  allow,deny
  Deny   from All
</FilesMatch>

It's also possible to block access to whole directories and directory trees. For example we don't want anyone to access any information outside /var/www/, /usr/share/apache2/icons/ and /home/user/public_html. While the current configuration only allows access to these directories, it's possible that a mistake in the future could mess this up. A better approach is to deny access to everything by default and then to explicitly all access as required. While we are at it, we'll also turn off Options and AllowOverride by default and only enable them as needed.

<Directory />
  Order Allow,Deny
  Deny from all
  Options None
  AllowOverride None
</Directory>

<Directory /srv/www>
  Order allow,deny
  Allow from all
  Options FollowSymlinks Indexes
  AllowOverride All
</Directory>

<Directory /home/*/public_html>
  Order Allow,Deny
  Allow from all
  Options Indexes
</Directory>

<Directory /usr/share/apache2/icons/>
  Order Allow,Deny
  Allow from all
  Options Indexes
</Directory>