How to Use Apache DirectoryIndex for Default Files?

The Apache DirectoryIndex directive specifies the default file the server looks for and serves when a user requests a directory instead of a specific file (for example, accessing example.com/ instead of example.com/index.html). By defining this directive in your server configuration or a .htaccess file, you can control the landing page of your website and establish a fallback hierarchy of filenames to check. This article covers how the directive works, where to configure it, and best practices for setting up your default files.

Understanding the DirectoryIndex Directive

When a web browser requests a URL that ends in a slash, Apache treats it as a directory request. Without a defined default index, the server will either look for a default file name pre-configured by your hosting provider, attempt to list all files in that directory (if Options Indexes is enabled), or return a 403 Forbidden error.

The DirectoryIndex directive tells Apache exactly which files to look for and in what order of preference. The syntax is straightforward:

DirectoryIndex filename1.html filename2.php filename3.txt

When a request comes in, Apache reads the list from left to right. It will serve the first file it finds. If filename1.html does not exist in the requested directory, it looks for filename2.php, and so on.

How to Configure DirectoryIndex

You can implement this directive in two primary places depending on your server access levels: the main server configuration files or a local .htaccess file.

1. In the Main Server Configuration (httpd.conf or apache2.conf)

If you have root access to your server, modifying the main configuration file is the most efficient method because it applies globally and avoids the performance hit of server-side .htaccess overrides.

DirectoryIndex index.php index.html home.html
sudo systemctl restart apache2

2. In a Local .htaccess File

If you are on shared hosting or do not have access to the main configuration files, you can manage this setting on a per-directory basis using an .htaccess file.

DirectoryIndex welcome.html index.html

Advanced Usage and Best Practices

To get the most out of the DirectoryIndex directive, keep these configuration strategies in mind:

Options -Indexes
DirectoryIndex index.html index.php