仅在找不到文件时才重定向请求?

时间:2009-02-27 14:34:55

标签: apache .htaccess mod-rewrite

我希望有一种方法可以用mod_rewrite和Apache做到这一点,但也许还有另一种方法可以考虑。

在我的网站上,我为客户端设置了重新设置网站版本的目录。如果Web根目录为/home/blah/www,则客户端目录为/home/blah/www/clients/abc。当您通过Web浏览器访问客户端目录时,我希望它在客户端目录中使用任何请求的文件(如果存在)。否则,我希望它使用Web根目录中的文件。

例如,假设客户端不需要自己的index.html。因此,某些代码会确定index.html中没有/home/blah/www/clients/abc,而是使用/home/blah/www中的/clients/abc。请记住,我不想随时将客户端重定向到Web根目录,如果客户端目录没有指定自己的副本,我只想使用具有该名称的Web根目录。 Web浏览器仍应指向news.html文件是存在于根目录中还是存在于根目录中。同样,如果客户端目录中有news.html请求且确实存在,那么只需提供该文件而不是Web根目录.htaccess。用户的体验应该是无缝的。

我需要这个来处理任何文件名的请求。例如,如果我需要为{{1}}为我可能想要重定向的每个文件添加一个新行,它就会失去目的,因为需要太多的维护,并且鉴于大量的数据很有可能出错文件。

在您的示例中,请指明您的代码是否位于客户端目录中的.htaccess文件或Web根目录中。 Web root是首选。

6 个答案:

答案 0 :(得分:25)

# If requested resource exists as a file or directory, skip next two rules
RewriteCond %{DOCUMENT_ROOT}/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule (.*) - [S=2]
#
# Requested resource does not exist, do rewrite if it exists in /archive
RewriteCond %{DOCUMENT_ROOT}/archive/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/archive/$1 -d
RewriteRule (.*) /archive/$1 [L]
#
# Else rewrite requests for non-existent resources to /index.php
RewriteRule (.*) /index.php?q=$1 [L] 

来自Rewrite if files do not exist

答案 1 :(得分:10)

这个怎么样?

# If requested resource exists as a file or directory go to it
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*) - [L]

# Else rewrite requests for non-existent resources to /index.php
RewriteRule (.*) /index.php?q=$1 [L]

答案 2 :(得分:5)

上面的每个例子我似乎至少有一个问题。 %{DOCUMENT_ROOT}似乎在某些地方做错了,有些/字符似乎丢失了。这是我的解决方案,它位于Web根目录中的.htaccess

不是使用两个规则(一个用于找到clients /下的文件,一个用于未找到的文件),我需要检查的是所请求的文件(或目录)是否不存在。因为如果存在,则不需要进行任何更改,它只能使用客户端目录中提供的文件。这是我确定的代码:

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/clients/$1/$2 !-f
RewriteCond %{DOCUMENT_ROOT}/clients/$1/$2 !-d
RewriteRule ^clients/([^/]+)/(.*)$ $2 [L]

感谢您的帮助!

答案 3 :(得分:3)

RewriteCond %{REQUEST_FILENAME} !-f

答案 4 :(得分:0)

试试这个:

RewriteEngine on
RewriteRule ^clients/abc/ - [L]
RewriteCond %{DOCUMENT_ROOT}clients/abc/$0 -f
RewriteRule .* clients/abc/$0 [L]

答案 5 :(得分:0)

我认为你想要这些内容:

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}clients/$1/$2 -f
RewriteRule ^clients/([^/]+)/(.*)$ %{DOCUMENT_ROOT}clients/$1/$2 [L]
RewriteRule ^clients/([^/]+)/(.*)$ %{DOCUMENT_ROOT}$2 [L]
相关问题