.htaccess - try all DirectoryIndex and rewrite if file doesn't exist .htaccess - try all DirectoryIndex and rewrite if file doesn't exist apache apache

.htaccess - try all DirectoryIndex and rewrite if file doesn't exist


How can I both try all DirectoryIndex files AND redirect missing files to the home page?

I don't think that's possible with mod_rewrite or mod_alias modules. You have to look for other options to solve the problem. Here is an idea using the same DirectoryIndex directive to force the loading of a file at root directory as the last option:

Place this line in one .htaccess file at root directory:

DirectoryIndex  index.php  index.html  /missing.php

Create missing.php in root directory with these lines of code:

<?phpheader("Location: http://www.example.com/"); // Redirect?>

No additional directives or rules are needed. missing.php at root directory will be loaded if none of the previous files (From left to right) is found at the target directory. All requests must have a trailing slash for this to work, though.

missing,php is just an example. Any file name can be used.

UPDATED with additional option:

According to OP comment:
"But how do I handle missing files such as example.com/file-not-on-server.php"

In this case, mod_rewrite is indeed a solution.

You may try this in the .htaccess file at root:

# Directive that solves the original questionDirectoryIndex  index.php  index.html  /missing.phpOptions +FollowSymlinks -MultiViewsRewriteEngine OnRewriteBase /# Next condition is met when the requested file doesn't existRewriteCond %{REQUEST_FILENAME} !-f# If previous condition was met, use the next ruleRewriteRule ^(.*)$         /index.php [L,NC]

NOTES:
1. /index.php in the rule, is just an example. It can be any file.
2. For permanent redirection, replace [L,NC] with [R=301,L,NC].