.htaccess 重定向以使用查询删除重复的字符串

问题描述 投票:0回答:1

假设我有以下网址:

https://mywebsite.com/pages.html?limit=24&start=7440&t=3349.html.html.html

https://mywebsite.com/pages.html.html.html?limit=24&start=8136&t=3358

https://mywebsite.com/pages.html.html?limit=24&start=8136&t=3358.html.html.html.html

如何去掉重复的“.html”部分,只留下一个?

这是一个混合情况,经过两个小时的努力,我仍然找不到使用正确的正则表达式来使其工作的方法。

这是我尝试过的:

RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} ^(.*)((.html){2,})(.*)$
RewriteRule ^(.*)$ https://mywebsite.com/%1%4 [QSA,R=302,L]

我使用 302,因为它是一个临时解决方法,直到我找到解决此问题根源的有效解决方案,但我不断遇到重定向循环。

我想只保留一个 .html,删除所有多次出现的 .html。

示例1:

https://mywebsite.com/pages.html?limit=24&start=7440&t=3349.html.html.html

should redirect to:

https://mywebsite.com/pages.html?limit=24&start=7440&t=3349.html

https://mywebsite.com/pages.html.html?limit=24&start=8136&t=3358.html.html.html.html

should redirect to:

https://mywebsite.com/pages.html?limit=24&start=8136&t=3358.html

很抱歉提出这个问题,但这对我来说特别棘手,我找不到解决方案。

提前致谢。

.htaccess redirect
1个回答
0
投票
RewriteCond %{QUERY_STRING} ^(.*)((.html){2,})(.*)$
RewriteRule ^(.*)$ https://mywebsite.com/%1%4 [QSA,R=302,L]

这里有几个问题:

  • 您将丢弃原始 URL 路径(即
    /pages.html
  • 您正在将更正后的查询字符串(即
    %1%4
    )移动到 URL 路径(而不是查询字符串)中。如果应该是
    ?%1%4
  • 然后再次附加原始的“不正确”查询字符串(无论
    QSA
    标志如何)。这最终会导致重定向循环。
  • 如果
    .html
    在查询字符串中仅重复一次,则会失败。 (这会发生吗,就像 URL 路径中出现的那样?)

在您的示例中,多个

.html
始终出现在 URL 末尾和/或查询字符串末尾。因此,正则表达式中的尾随
(.*)
似乎是不必要的(因为在重复的
.html
序列之后什么也没有发生)。

尝试以下方法:

# Multiple ".html" at end of query string
# (Also resolves multiple ".html" at end of URL-path - if any)
RewriteCond %{QUERY_STRING} (.+?\.html)(\.html)+$
RewriteRule (.+?\.html)(\.html)*$ /$1?%1 [NE,R,L]

# Multiple ".html" at end of the URL-path only
# (Query string + URL-path already handled by the above rule.)
RewriteRule (.+?\.html)(\.html)+$ /$1 [R,L]

这 2 条规则最多只有 1 个重定向。第一条规则处理查询字符串中错误的多个

.html
,同时更正 URL 路径。第二条规则仅处理 URL 路径(当查询字符串已经正确时)。

这两个规则都不需要

QSA
标志。在第一条规则中,我们重建查询字符串,因此原始查询字符串被丢弃(默认情况下)。在第二条规则中,默认情况下会传递查询字符串(已经确定)。

自反向引用以来,第一个规则中使用了

NE
(从
QUERY_STRING
服务器变量捕获的内容已进行 URL 编码)。

单个

R
标志默认为 302(临时)。

© www.soinside.com 2019 - 2024. All rights reserved.