Disable Directory Indexes and Handle 403 Errors with .htaccess

The websites I develop for normally display the contents of a folder when an index file, like index.php, isn't present. This setup may work for some websites, but not the ones I work on. Instead of adding unnecessary index pages to prevent this type of activity, let's look at how the .htaccess file can help.


For those unfamiliar, one benefit of an index file is it allows for shorter links. Instead of making visitors type "www.examplewebsite.com/about.php", you could add an "about" folder containing an index file. Visitors can then go to "www.examplewebsite.com/about/".

The problem is that there are folders which are unlikely to have an index file. When going to "www.examplewebsite.com/images/", for example, there probably won't be an index file. So instead of displaying a page, it lists what's inside the folder (see Figure 1).

Chrome screenshot showing a directory index
Figure 1. Example Directory Index

This view may be useful for some visitors, but it's going confuse and frustrate others. Plus, listing the files presents a slight security risk. There may be files in the folder that we don't want others to know about. Of course, it's better to keep these files outside of the root directory so they are inaccessible to the browser. But if the files are within the root directory, you'll want to disable directory indexes.

Disable Directory Indexes

To prevent the website from listing the contents of a folder, we can add the following line to the .htaccess file:

Options -indexes

403 Forbidden Errors

With directory indexing turned off, we now have another problem. The not-so-friendly system errors are back (see Figure 2).

Chrome screenshot showing the 403 error message
Figure 2. Error 403 Message

We could create a specialized error page like we did previously (Create Error 404 Page with .htaccess). However, this 403 error message is basically a 404 error in disguise. After all, the website is looking for an index file which isn't there. So let's add some lines to the .htaccess file to handle both 404 and 403 errors.

Options -indexes
ErrorDocument 404 /errors/404.php
ErrorDocument 403 /errors/404.php

Note that both ErrorDocument statements should point to your Error 404 page as discussed in the previous post.


All that's left to do is upload the .htaccess file to your root directory. If your root directory already contains an .htaccess file, make sure your new version contains the code from the old one. If everything's set up correctly, folders without index files should now redirect to your Error 404 page.

Note that your page indexes should still work. The .htaccess code only disables directory indexes. If you have any links like "www.yourwebsite.com/about/", they should still display your About page.


There are currently no comments.

Leave a Comment