How to Prevent or Allow Directory Listing

The contents of this article may be out of date. It has been archived and will no longer be updated, comments are closed and the page is provided for reference purposes only.

Having a list of files in a directory on your site sometimes is useful. You may for example want a directory you can upload large files to for others to download without wanting to spend time creating a fancy PHP (or your preferred language) interface. It is important to understand the security implications of allowing directory listings. Listing files in directories that contain your code will make it easier for someone to compromise your site. We recommended you restrict listings to specific folders. You can easily control this behaviour on your Apache server using one simple line in a .htaccess file.

The easiest way to create this file is to open your favourite text editor and create a new plain text document named htaccess.txt. Add the appropriate line or lines from below and save. Upload the file using an FTP client then rename the file to .htaccess. The period at the beginning tells the system this is a hidden file hence if you create the file on a Mac the file will be automatically be hidden if you save it as .htaccess initially. Windows users should have no such problems.

If you upload the .htaccess file to the public htdocs folder the file will control how the whole site behaves, as mentioned above this is usually not a good idea. Saving the file to a directory below the top level folder will then only control the behaviour the containing directory e.g. uploading the file to a directory /htdocs/sharedfiles/ will then only allow the contents of the “sharedfiles” directory to be listed.

Add any combination of the following to you .htaccess file:

Options +Indexes

The above line enables Directory listing.

Options –Indexes

The above disables directory listing for your web site or folder.

IndexOptions +FancyIndexing

To make your listing look fancier add the above.

Fancy Directory Listing

The above shows an example of a fancy directory listing accessed with Safari.

The .htaccess file allows you some greater control over the files that are listed.

With .htaccess file you can control which files to be ignored when creating a directory list as in the example below.

IndexIgnore *.gif *.zip *.txt

Will make the apache server to skip all gif, zip and txt files from the directory list.

IndexIngnore *

Will just create an empty directory list.

This article was posted on 13 November 2009 in Misc, Tutorials

That's the end of this article. I hope you found it useful. If you're enjoyed this article why don't you have a look around the archives, where you can find some more tutorials, tips and general ramblings.