My .htaccess file contains the following directives
DirectoryIndex index.html index.php
# redirect invalid requests and missing files to the home page
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://www.mydomain.com/ [L]
The problem is that many programmers(loosely used term) worked on this site. Some directories use index.html and some use index.php.
If a directory uses index.php, the request to www.mydomain.com/directory looks for www.mydomain.com/directory/index.html and is redirected to www.mydomain.com before it can look for www.mydomain.com/directory/index.php
How can I both try all DirectoryIndex files AND redirect missing files to the home page?
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:
<?php
header("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.
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 question
DirectoryIndex index.php index.html /missing.php
Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /
# Next condition is met when the requested file doesn't exist
RewriteCond %{REQUEST_FILENAME} !-f
# If previous condition was met, use the next rule
RewriteRule ^(.*)$ /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].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With