根上查询字符串的 301 重定向?

301 Redirect for Query String on Root?

我已经尝试了多种方法来尝试使用根上的查询字符串重定向一些 URLs,例如,如果我尝试匹配 URL http://example.com/?bloginfo=racing

Redirect 301 "/?bloginfo=racing" http://example.com/racing

RedirectMatch 301 ^/?bloginfo=racing$ http://example.com/racing

条件永远不会匹配。在我的 .htaccess 文件中是否有一个好的方法来编写这种重定向?

如果要匹配查询字符串,您需要使用 mod_rewrite 并在 RewriteCond 指令中检查 QUERY_STRING 服务器变量。 mod_alias 指令(即 RedirectRedirectMatch 仅匹配 URL 路径,不匹配查询字符串。

例如,要将 http://example.com/?bloginfo=racing 重定向到 http://example.com/racing,您可以执行如下操作:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^bloginfo=racing$
RewriteRule ^$ /racing? [R=302,L]

为了从请求中删除查询字符串,替换 上的尾随 ? 是必需的,否则,它将传递给目标 URL.或者,在 Apache 2.4+

上使用 QSD 标志

将 302(临时)更改为 301(永久),如果这是永久性的,并且只有当您确定它工作正常时(以避免缓存问题)。

为了使它更通用并将 /?bloginfo=<something> 重定向到 /<something> 然后您可以执行以下操作:

RewriteCond %{QUERY_STRING} ^bloginfo=([^&]+)
RewriteRule ^$ /%1? [R=302,L]

%1 是对上次匹配中捕获的子模式的反向引用 CondPattern.

查询字符串是独立于请求 URI 的变量,因此您必须执行如下操作:

RewriteEngine On
RewriteCond %{QUERY_STRING} bloginfo=racing 
RewriteRule ^$ /racing [L,R]