.htaccess:将所有请求重定向到子目录,除非存在确切的目录

时间:2010-08-21 22:37:55

标签: .htaccess redirect

www.example.com/*的任何请求都必须重定向到www.example.com/blog/*

如果没有www.前缀,请添加它。

重要的是,如果存在与请求URI匹配的任何目录,请不要重定向。

示例:

(www.)example.com/<request> - &gt; www.example.com/blog/<request><request> === <dirname>

之外的{{1}}

遵循以上3个条件,我如何编码.htaccess?请帮忙! 谢谢; - )

1 个答案:

答案 0 :(得分:12)

这应该做你想要的。我还添加了“如果此文件存在则不重定向”,因为我不确定您现有目录中的内容。如果您不想要它,可以尝试删除第二个RewriteCond,但我认为这可能在某种程度上是必要的。

RewriteEngine On

# Check if the requested path is not a real file or a
# real directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# If the current request doesn't start with "blog", and
# it's not a real file or directory based on the above
# conditions, add "blog" to the front of the request, and
# mark an environment variable that indicates we'll need
# to redirect
RewriteRule !^blog blog%{REQUEST_URI} [E=CHANGED:TRUE]

# Check if the host doesn't start with "www.", or if we've
# marked the change variable above, since in either of those
# cases we need to perform a redirection (We do it this way,
# since we'll at most send one redirect back to the client,
# instead of the potential two we might send if we didn't
# combine the checks)
RewriteCond %{HTTP_HOST}  !^www\. [OR]
RewriteCond %{ENV:CHANGED} =TRUE
# Capture the non-"www." part of the host, regardless of
# whether or not the "www." is there
RewriteCond %{HTTP_HOST}   ^(www\.)?(.*)$
# Redirect anything to the corrected URL, using the
# backreference from the above condition, and the entirety of
# the requested path (possibly modified by the above RewriteRule)
RewriteRule ^.*$   http://www.%2/$0 [R=301,L]