【问题标题】:.htaccess: Redirect all requests to a subdirectory except if an exact directory exists.htaccess:将所有请求重定向到子目录,除非存在确切目录
【发布时间】:2010-08-22 09:52:57
【问题描述】:

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

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

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

例子:

(www.)example.com/<request> -> www.example.com/blog/<request> 除了<request> === <dirname>

根据上述 3 个条件,我如何编写 .htaccess?请帮忙! 谢谢 ;-)

【问题讨论】:

    标签: .htaccess redirect


    【解决方案1】:

    这应该可以满足您的要求。我还添加了“如果此文件存在则不要重定向”,因为我不确定现有目录中有什么。如果你不想要它,你可以尝试通过取出第二个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]
    

    【讨论】:

    • 一切正常...谢谢。嘿,可能如果您可以简要解释一下添加 cmets 的每一行,那就更好了。无论如何,再次感谢。
    • @Drigit Inrok - 很好,我现在添加了 cmets,希望能解释一切。
    猜你喜欢
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 2013-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    相关资源
    最近更新 更多