RewriteRule 删除多余的单个“?”在 URL

RewriteRule to remove superfluous single "?" in URL

我正在使用 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".

问号是正则表达式的特殊字符,表示"the preceding character is optional"。您的规则实际上匹配 index.htm 或 index.html.

相反,尝试将问号放在 "character class" 中。这个似乎对我有用:

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

$ 表示字符串结尾,如 ^ 表示字符串开头)

参见 http://publib.boulder.ibm.com/httpserv/manual60/mod/mod_rewrite.html(您的 Apache 版本不是最新的)

注意我们之前的尝试,转义问号似乎不起作用。

另外,我会向 CDN 推送问号发送的原因。这似乎不是一个正常的模式。

您需要使用一个技巧,因为 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]