Apache mod_rewrite。当文件不存在时能够“故障转移”吗?

Apache mod_rewrite。当文件不存在时能够“故障转移”吗?

我正在尝试配置 mod_rewrite 以尝试按特定顺序加载/提供文件。我认为描述我试图实现的目标的最简单方法是举个例子。

假设我的文档根目录中存在以下文件/文件夹:

/missing.html
/subdomain.example.com/index.html
/subdomain.example.com/other_page.html
/folder1/index.html
/folder1/other_page.html

按顺序,返回的文件应该是:1)请求的文件夹/路径 2)请求的文件夹/路径,前面加上主机名 3)'missing.html' 文件

例如:

http://example.com/folder1/ -> /folder1/index.html
http://example.com/folder1/other_page.html -> /folder1/other_page.html
http://example.com/folder1/nonexistant_file.html -> /missing.html
http://subdomain.example.com/ -> /subdomain.example.com/index.html
http://subdomain.example.com/other_page.html -> /subdomain.example.com/other_page.html 
http://subdomain.example.com/nonexistant_file.html -> /missing.html
http://some_other_subdomain.example.com/ -> /missing.html

到目前为止,我已经设法使它基本正常工作,但我在“missing.html”部分遇到了麻烦。我期望处理的任何内容都会导致 500 错误。

我不明白是否可以仅使用 mod_rewrite 来完成我想要实现的目标... 文档对我来说没有多大意义!

以下是我的 .htaccess 文件:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule (.*) $1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) %{HTTP_HOST}/$1 [L,QSA]

RewriteRule (.*) missing\.html [L]

任何投入将不胜感激!

迈克尔

答案1

这套规则实现了我想要实现的目标

RewriteEngine On
RewriteBase /

# File exists? Do nothing!
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .* - [L,QSA]

# If we haven't redirected yet, perform internal redirect to /domain/
RewriteCond %{ENV:domain_rewritten} "!=1"
RewriteCond %{ENV:REDIRECT_domain_rewritten} "!=1"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/%{HTTP_HOST} -d
RewriteRule (.*) %{HTTP_HOST}/%{REQUEST_URI} [L,QSA,E=domain_rewritten:1]

# Redirect above didn't work...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) missing\.html [L]

相关内容