Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 805
csi Avatar asked Dec 19 '25 20:12

csi


1 Answers

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.

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 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].

like image 176
Felipe Alameda A Avatar answered Dec 21 '25 12:12

Felipe Alameda A