How can I create a simple index.html file which lists all files/directories?

David B picture David B · Sep 24, 2010 · Viewed 153.9k times · Source

We use a web server that does not allow directory listing.

There is a specific directory I would like to allow listing of.

How can make a simple HTML file that will contain the contents of this directory?

Answer

ccpizza picture ccpizza · Sep 23, 2017

There are enough valid reasons to explicitly disable automatic directory indexes in apache or other web servers. Or, for example, you might only want to include certain file types in the index. In such cases you might still want to have a statically generated index.html file for specific folders.

This can be easily achieved with tree - a minimalistic utility that is available on most unix-like systems (ubuntu/debian: sudo apt install tree, mac: brew install tree) and which can generate plain text, XML, JSON or HTML output.

Generate an HTML directory index one level deep:

tree -H '.' -L 1 --noreport --charset utf-8 > index.html

Only include specific file types that match a glob pattern, e.g. *.zip files:

tree -H '.' -L 1 --noreport --charset utf-8 -P "*.zip" > index.html

The argument to -H is what will be used as a base href, so you can pass either a relative path such as . or an absolute path from the web root, such as /files. -L 1 limits the listing to the current directory only.

I needed an index generator which I could style the way I want, and which would also include the file sizes, so ended up using this script — in addition to having customizable styling, the script can also recursively generate an index.html file in all the nested subdirectories.

Update: an updated version (python 3) of the index generation script that uses cleaner styling (inspired by caddyserver's file-server module), includes last modified time and is more responsive in mobile viewports.