【问题标题】:htaccess - cut out the question mark if there is one at the endhtaccess - 如果末尾有一个问号,请去掉问号
【发布时间】:2021-10-12 23:36:21
【问题描述】:

有这样的代码

<IfModule mod_rewrite.c>
RewriteCond %{QUERY_STRING} !^$
RewriteCond %{QUERY_STRING} !(^|&)srp=
RewriteCond %{QUERY_STRING} !(^|&)q=
RewriteRule ^(.+?)\.html$ https://%{HTTP_HOST}/$1.html? [L,R=301]
</IfModule>

<IfModule mod_rewrite.c>
RewriteRule ^(.+?)\.html(?!/amp/).+$ https://%{HTTP_HOST}/$1.html? [L,R=301]
</IfModule>

效果很好,但是如果链接是这样的:

website.com/post.html?

在这种情况下,问号仍然存在。在这种情况下如何删除它?

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    您不能简单地检查空查询字符串,因为 QUERY_STRING 服务器变量已定义且为空,无论尾随 ? 是否存在。

    要删除 URL 路径末尾的杂散 ?(本质上是一个空查询字符串),您可以检查 THE_REQUEST 服务器变量。例如:

    RewriteCond %{THE_REQUEST} \s[^?]*\?\s
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [QSD,L,R=301]
    

    QSD(查询字符串丢弃)标志删除查询字符串。这是在 Apache 2.4 上删除查询字符串的首选方法,而不是将 ? 附加到 substitution 字符串。

    THE_REQUEST 包含 HTTP 请求标头的第一行,并包含以下形式的字符串:

    GET /post.html? HTTP/1.1
    

    因此,正则表达式 \s[^?]*\?\s 匹配文字 ?,后跟 URL 路径末尾的 空格(避免可能出现在非结尾的 ? -空查询字符串)。例如:

    • /post.html? 重定向到 /post.html
    • /post.html?foo=1? - 没有重定向,因为最后的 ?foo URL 参数的一部分。

    旁白: 除非指令是可选的,否则不应将 &lt;IfModule mod_rewrite.c&gt; 包装器中的每个块都括起来。 (即使这样,指令也应该组合在一起。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      相关资源
      最近更新 更多