Securing Apache and Maintaining Usability
First, you should always avoid .htaccess and use it as a last resort. Still, this example holds whether or not you are using .htaccess.
Let’s say you have a directory you wish to secure so that only the index and some file (test.txt) is available. Other other content in the directory should be denied. For example:
These links should load:
- www.example.com/foo
- www.example.com/foo/
- www.example.com/foo/test.txt
In addition, the link without the trailing / should redirect to the link with the trailing / (from /foo to /foo/) for ease of access for your users.
These links should give a 403:
- www.example.com/foo/bar
- www.example.com/foo/letmein.txt
To accomplish this, you might write a .htaccess as follows:
Apache 2.2
Order allow,deny <Files ~ ^$|^index.html$|^test.txt$> Order deny,allow </Files>
Apache 2.4
Require all denied <Files ~ ^$|^index.html$|^test.txt$> Require all granted </Files>
However, you will run into a problem: The link without a trailing / will not work (www.example.com/foo) because permissions are evaluated before the mod_dir module’s DirectorySlash functionality evaluates whether or not this is a directory. While not intuitive, we also must add the directory as a file name to be allowed as follows:
Apache 2.2
Order allow,deny <Files ~ ^foo$|^$|^index.html$|^test.txt$> Order deny,allow </Files>
Apache 2.4
Require all denied <Files ~ ^foo$|^$|^index.html$|^test.txt$> Require all granted </Files>
Hopefully this will help anyone else dealing with a similar issue because it took us a lot of troubleshooting to pin this down. Here are some search terms you might try to find this post:
- Apache 403 does not add trailing /
- Apache does not add trailing slash
- .htaccess deny all breaks trailing directory slash
- .htaccess Require all denied breaks trailing directory slash
-Eric