【问题标题】:htaccess 301 redirect www & non-www to non-www subfolderhtaccess 301 将 www 和非 www 重定向到非 www 子文件夹
【发布时间】:2011-04-17 08:42:21
【问题描述】:

我正在尝试将 www 和非 www 重定向到非 www 子文件夹 /forums。

我目前正在使用此代码:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [OR]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ http://example.com/forums/$1 [R=301,L]

它运行良好,但存在一些问题。

如果我输入 URL:example.com,它会将我带到 example.com/forums。 -好的

如果我输入 URL:example.com/test,它会将我带到 example.com/test。 -好的

如果我输入 URL:www.example.com,它会将我带到 example.com/forums。 -好的

如果我输入 URL:www.example.com/test,它会将我带到 example.com/forums/test。 -错误

如何解决 www.example.com/test 出现的错误?

我希望 www.example.com/test 指向 example.com/test。

请帮帮我,谢谢!

【问题讨论】:

  • 这对我很有帮助,谢谢!

标签: apache .htaccess mod-rewrite redirect url-rewriting


【解决方案1】:

在您的 .htaccess 文件中尝试以下规则:

RewriteEngine on
Options +FollowSymlinks -MultiViews

# redirect empty URL to /forums
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^$ http://example.com/forums [R=301,L]

# non forums handler
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/forums [NC]
RewriteRule ^(.+)$ http://example.com/$1 [R=301,L]

【讨论】:

    【解决方案2】:

    如果您没有任何其他子域指向同一目录(或者它们也被重定向也没关系),那么您可以简单地试试这个:

    RewriteEngine On
    RewriteRule ^$ /forums/ [R=301,L]
    

    这会将所有对 www.example.com/ 和 example.com/ 的请求重定向到子文件夹 /forums/ 并保持所有其他请求不变。

    假设您给定的测试用例是唯一需要考虑的,那么这应该可行。如果您有任何其他情况,则可能需要扩展规则。

    【讨论】:

    • 谢谢,但效果不佳。我输入了 www.example.com/test,它给了我 www.example.com/test。我需要它是 example.com/test。
    • 好的,这在您编辑之前并不明显。我建议尝试另一个看起来不错的给定答案。
    猜你喜欢
    • 2014-04-09
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    相关资源
    最近更新 更多