首页 > 解决方案 > RewriteRule 删除多余的单个“?” 在网址中

问题描述

我正在使用 IBM HTTP 服务器配置文件来重写从 CDN 重定向的 URL。

出于某种原因,即使没有任何查询字符串,URL 也会带有一个多余的单个问号。例如:

/index.html?

我正在为此进行 301 重定向。我想删除单个“?” 来自 url,但如果有任何查询字符串,请保留它。

这是我尝试过的,但它不起作用:

RewriteRule ^/index.html? http://localhost/index.html [L,R=301]

更新:我用正确的正则表达式尝试了这个规则,但它也永远不会被触发。

RewriteRule ^/index.html\?$ http://localhost/index.html [L,R=301]

我尝试编写另一条规则将“index.html”重写为“test.html”,然后输入“index.html?” 在浏览器中,它将我重定向到“test.html?” 但不是“index.html”。

标签: regexapachehttpmod-rewriteibmhttpserver

解决方案


您需要使用一个技巧,因为 RewriteRule 仅与 URL 的路径组件隐式匹配。诀窍是查看未解析的原始请求行:

RewriteEngine ON
# literal ? followed by un-encoded space.  
RewriteCond %{THE_REQUEST} "\? "
# Ironically the ? here means drop any query string.
RewriteRule ^/index.html /index.html? [R=301]

推荐阅读