Apache2: Allow directory indexing, but restrict file access by type

.htaccessaccess-control-listapache-2.2configurationdirectoryindex

I need to configure my Apache2 server (version 2.2.22) such that I allow auto-indexing of the WWW root folder and its sub-directories, but restrict access (i.e. restrict download) to just a set of specific file types (i.e. .txt and .log). In other words, anybody can see what files are present, but only certain file types can be downloaded.

I have come up with the following which does restrict download to just the specified file types, but all URLs for a directory index return 403 Forbidden.

<Directory /var/www/>
    Options Indexes FollowSymLinks
    SetOutputFilter DEFLATE
    AllowOverride None
    Order allow,deny
    <FilesMatch "">
        Order deny,allow
        allow from all
    </FilesMatch>
    <FilesMatch ".+\.(?!(txt|log)$)[^\.]+?$">
        Order allow,deny
        deny from all
    </FilesMatch>
</Directory>

Best Answer

You need also to allow index files:

<FilesMatch "^index\.">
    Order allow,deny
    allow from all
</FilesMatch>

because Apache will search for them (like index.html, index.cgi,...) but they are all forbidden. I'm not sure why, but I suppose Apache cannot even check for existence of those files, and then sends a 403. If Apache can check the inexistence of those index files, he will create the directory index, and that needs the <FilesMatch ""> Directive, as the index file name is "".

You can find the information in the error logfile, some lines like:

client denied by server configuration: /var/www/index.html

And because you want that forbidden files are listed too, you need to add:

IndexOptions ShowForbidden

for example after Options Indexes FollowSymLinks. There are plenty of options for directory indexes you can find them in the apache doc.

Hope this helps.