首页 > 解决方案 > .htaccess 重定向规则不按顺序执行

问题描述

我的 .htaccess 文件如下所示:

RewriteEngine On
RewriteBase /
Redirect 301 /old/path/ https://www.newdomain.com/new/
# and a lot of other redirects

RewriteCond %{HTTP_HOST} !www.newdomain.com$ [NC]
RewriteRule ^(.*)$ https://www.newdomain.com/$1 [L,R=301]

我把它放在旧域的根目录中。

我希望当我输入https://www.olddomain.com/old/path/规则时Redirect 301 /old/path/ https://www.newdomain.com/new/首先触发,因此新的 URL 将是https://www.newdomain.com/new/.

相反,它被重定向到https://www.newdomain.com/old/path/.

如果我删除最后一个重定向,一切都会像预期的那样工作,所以新的 URL 是https://www.newdomain.com/new/. 但是我需要最后一个重定向,因为我还希望将子页面重定向到我没有专门为其设置重定向的新域。

标签: apache.htaccessredirect

解决方案


我修改了你的规则,请检查:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteRule ^old\/path\/$ https://www.newdomain.com/new/ [R=301,L]

    RewriteCond %{HTTP_HOST} !www.newdomain.com$ [NC]
    RewriteRule ^(.*)$ https://www.newdomain.com/$1 [R=301,L]
</IfModule>

推荐阅读