Last Updated on August 11, 2021 by Amit
In this article we will learn about the Apache DirectoryIndex a directive provided by Apache directory module . I will show you why we use ans how to use this directive in an htaccess or server.config file. Many of my htaccess article readers were requesting me to write a short post on “DirectoryIndex” and then I thought it would be worth posting an article on this so that it can help people on the internet.
DirectoryIndex directive in Apache
DirectoryIndex is part of Apache mod_dir. A directory module provided by Apache httpd server.
We use DirectoryIndex in an htaccess or server configuration file to set a custom index file for the directory so that the file can be served when a directory is requested.
The default behaviour on Apache server is to serve a file that has a name starting with index . For example if a directory has index.html file then this file will automatically be served while requesting the directory and if no such files are found then the directory structure is shown.
With DirectoryIndex it is possible to use a custom file as index. You can set any file as index.
The following is an example :
If you put the following line to your root htaccess , your server will show you demo.php file if you request your root folder ie /:
By default , your Apache server will serve index.html or index.php file as index but if you if you use the DirectoryIndex line above then Apache will read it and serve demo.php ignoring the files in your directory that start with index
You can use multiple files in DirectoryIndex
More then one file can be added to DirectoryIndex directive , something like the following :
DirectoryIndex demo.php somefile.php
You can use multiple files as backup so that if the first doesn’t exist then the second is served.
DirectoryIndex directive reads files from left to right. The file in first position is served if it exists otherwise the next file is checked .
If none of the specified files exists then you will see a normal 403 forbidden error while requesting a directory path.
You server may return directory list if the DirectoryIndex directive failed and you are using Options +Indexes in your htaccess.
DirectoryIndex maps your current folder path to the file specified as its target.
For example , the following line will map your current directory path , say /
You will see the contents of /demo.php file on the typed directory URL path / .
But if you want the URL to change , then you can use another mod-dir directive DirectoryIndexRedirect along with DirectoryIndex .
I hope this article was helpful! Thanks so much for reading!