Apache mod_rewrite 保留查询字符串并添加锚点

Apache mod_rewrite preserving query string and adding anchor

我想创建一个 mod_rewrite 规则来重定向这个: www.domain.com/original/

为此附上锚点: www.domain.com/new/#something-else

如果存在,它还应保留原始 URL 中指定的任何查询字符串。例如: www.domain.com/original/?key=example

应该重定向到: www.domain.com/new/?key=example#something-else

我尝试使用以下带有 NE 和 QSA 标志的 mod_rewrite 规则,即使它保留了锚点和查询字符串,它们也会以错误的顺序重写:查询字符串 after 锚而不是之前。

RewriteRule ^original https://%{HTTP_HOST}/new/#something-else [QSA,NE,R=301,L]

如何保留原始查询字符串(如果存在)并将锚点附加到末尾?

谢谢

How can I preserve the original query string (when present) and append the anchor to the end?

除非您在重定向中修改查询字符串,否则不需要标记 QSA,因此可以在此处省略。

您的规则中无需使用 https://%{HTTP_HOST},因为源域和重定向域相同。

</code> 将为空,因为您没有在模式中捕获任何文本。</p> <p>您可以使用此重定向规则:</p> <pre><code># when query string is non-empty RewriteCond %{QUERY_STRING} . RewriteRule ^original/?$ /new/?%{QUERY_STRING}#something-else [NC,NE,R=302,L] # when query string is empty RewriteRule ^original/?$ /new/#something-else [NC,NE,R=302,L]

一旦您确认它工作正常,请将 R=302 替换为 R=301(永久重定向)