.htaccess - 尝试所有DirectoryIndex并在文件不存在时重写

时间:2013-03-29 20:00:23

标签: php apache .htaccess mod-rewrite redirect

我的.htaccess文件包含以下指令

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]

问题在于许多程序员(使用松散的术语)在这个网站上工作。有些目录使用index.html,有些使用index.php

如果目录使用index.php,则www.mydomain.com/directory的请求会查找www.mydomain.com/directory/index.html,并在找到www.mydomain.com之前重定向到www.mydomain.com/directory/index.php

我如何同时尝试所有DirectoryIndex个文件并将丢失的文件重定向到主页?

1 个答案:

答案 0 :(得分:2)

  

我如何同时尝试所有DirectoryIndex文件并重定向丢失的文件   到主页?

我认为mod_rewrite或mod_alias模块不可能。您必须寻找其他选项来解决问题。这是一个想法,使用相同的DirectoryIndex指令强制加载根目录下的文件作为最后一个选项:

将此行放在根目录下的一个.htaccess文件中:

DirectoryIndex  index.php  index.html  /missing.php

使用以下代码行在根目录中创建missing.php

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

不需要其他指令或规则。如果在目标目录中找不到任何先前的文件(从左到右),则将加载根目录下的 missing.php 。但是,所有请求都必须有一个尾部斜杠才能正常工作。

缺少,php 只是一个例子。可以使用任何文件名。

更新了附加选项:

  

根据OP评论
  “但我如何处理丢失的文件,例如example.com/file-not-on-server.php”

在这种情况下,mod_rewrite确实是一种解决方案。

您可以在root用户的.htaccess文件中尝试此操作:

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

注意:
1. /index.php在规则中,只是一个例子。它可以是任何文件 2.对于永久重定向,将[L,NC]替换为[R = 301,L,NC]。