【问题标题】:Browser going in a loop while using the 301 redirection浏览器在使用 301 重定向时进入循环
【发布时间】:2022-01-23 07:53:21
【问题描述】:

我正在使用 WordPress,我必须重定向一些 URL,例如

https://test.com/demo to https://test.com/demo/a/b/c/
https://test.com/example to https://test.com/example/a/b
https://test.com/xyz to https://test.com/xyz/a/b/c/d/

https://test.com/xyz/a/ to https://test.com/pqr/

我尝试了下面的 301 代码,但它不起作用,我的浏览器正在循环,并且 URL 显示多次。

Redirect 301 http://test.com/demo http://test.com/demo/a/b/c/
Redirect 301 http://test.com/example http://test.com/example/a/b
Redirect 301 https://test.com/xyz https://test.com/xyz/a/b/c/d/
Redirect 301 https://test.com/xyz/a/ https://test.com/pqr/

.ht 访问代码

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]


RewriteRule ^demo$ /demo/a/b/c/ [R=301,L
RewriteRule ^example$ /example/a/b/c/ [R=301,L]


</IfModule>
# END WordPress

【问题讨论】:

    标签: .htaccess redirect mod-rewrite


    【解决方案1】:

    您发布的指令不会做任何事情,因为 Redirect 指令将根相对 URL 路径作为 URL,而不是绝对 URL(带有方案 + 主机名) .您可能会看到缓存重定向的结果(301 - 永久 - 重定向由浏览器永久缓存。首先使用 302 进行测试以避免缓存问题。)

    但是,Redirect 指令不是该工作的正确工具,原因如下:

    • mod_alias Redirect 指令是前缀匹配的,因此匹配任何 开始 与规定的 URL 路径。 (因此,在您的示例中,前三个重定向确实会导致重定向循环,而第四个将永远不会被处理。)

    • 您应该避免在同一上下文中混合 mod_rewrite(WordPress 代码块的一部分)和 mod_alias,因为您可能会遇到意外的冲突。 mod_rewrite 总是先执行,尽管指令的顺序很明显。

    改用 mod_rewrite 在您的 .htaccess 文件顶部尝试以下操作。 之前 # BEGIN WordPress 代码块。

    RewriteRule ^demo$ /demo/a/b/c/ [R=301,L]
    RewriteRule ^example$ /example/a/b/c/ [R=301,L]
    RewriteRule ^xyz$ /xyz/a/b/c/ [R=301,L]
    RewriteRule ^xyz/a/$ /pqr/ [R=301,L]
    

    注意:RewriteRulepattern 匹配的 URL 路径上没有斜杠前缀。

    【讨论】:

    • 我测试了代码的第一行代码,但它没有重定向。检查他人
    • 确保清除所有缓存。如果仍然无法正常工作,请使用完整的.htaccess 文件更新您的问题,并附上这些指令。
    • 我清除了缓存并在私人浏览器中检查,但同样的问题。更新了问题中的代码
    • @user9437856 你把指令放错地方了。正如我在回答中所说,这些指令必须“在.htaccess 文件的顶部,在# BEGIN WordPress 代码块之前”。代码 cmets 中还有一个警告,您不应该手动编辑 WordPress 注释标记之间的代码。
    • 让我再检查一遍
    猜你喜欢
    • 1970-01-01
    • 2015-10-09
    • 2011-05-26
    • 1970-01-01
    • 2015-10-24
    • 2015-05-23
    • 2013-11-23
    • 1970-01-01
    • 2011-02-09
    相关资源
    最近更新 更多