Last Updated on April 12, 2021 by amitoverflow1
With htaccess it is quite possible to change the directory index file to any other file. By default a file that contains the index perfix is served as directory index handler by the server. But this behavior can be changed by using a one line of code in htaccess.
In this post you will learn how to use a different file as directory index . This quick three minute read tutorial will teach you all about adding a custom index file on Apache server.
Whenever you create a new directory , you create an index file like index.html or index.php . An index file is important as it prevents directory listing otherwise if this file is missing then directory structure may be visible to clients. To prevent this from happening , we use an index file in a web directory.
Since an index file is served as directory handler by default, you can change the file to any other file by manually adding a directive in your htaccess file. There are two ways to do this , one is using the DirectoryIndex directive provided by directory module and the another one is using a RewriteRule to rewrite the directory to a file.
Using DirectoryIndex directive to change the index file
One of the easiest and recommend way to change a directory index file is DirectoryIndex a directive provided by mod-dir. You can use the the following line to achieve this behavior:
This sets the demo.html file as directory index handler. Your server will show you the demo.html file content if you visit a directory even if the index.html is present in directory .
Using RewriteRule to change directory index file
You can also use RewriteRule directive to change the index file. For this you will need to rewrite your directory to the filename you want to be served as index.
RewriteRule ^dirname/$ /demo.php [L]
For the root directory , you can use `^$` in the pattern as the root is treated as an empty URI in htaccess context.
RewriteRule ^$ /demo.php [L]