重定向子文件夹并将查询字符串添加到结果 url

Redirecting subfolder AND adding a querystring to the resulting url

我已将 wordpress 安装从子文件夹移动到域根目录。 我已经通过 .htaccess 成功重定向了该子文件夹,但我完全无法向其添加查询字符串,因此我知道客户端何时来自旧的 link,同时保留请求所具有的任何先前查询字符串。

我在 .htaccess 文件中 wordpress 指令后的(唯一)代码是:

<IfModule mod_rewrite.c>
RewriteEngine On    
RewriteCond %{HTTP_HOST} ^nbek.org/blog$ [OR]
RewriteCond %{HTTP_HOST} ^nbek.org/blog/$
RewriteRule (.*)$ https://nbek.org/?sublog=nox [R=301,QSA,L]
</IfModule>

我也试过:

<IfModule mod_rewrite.c>
RewriteEngine On    
RewriteCond %{HTTP_HOST} ^nbek.org/blog$ [OR]
RewriteCond %{HTTP_HOST} ^nbek.org/blog/$
RewriteRule ^(.*)$ ?sublog=nox [QSA]
RewriteRule (.*)$ https://nbek.org/ [R=301,L]
</IfModule>

完全没有成功。我做错了什么?

The (only) code I have in the .htaccess file after the wordpress directives is:

<IfModule mod_rewrite.c>
RewriteEngine On    
RewriteCond %{HTTP_HOST} ^example.com/blog$ [OR]
RewriteCond %{HTTP_HOST} ^example.com/blog/$
RewriteRule (.*)$ https://example.com/?sublog=nox [R=301,QSA,L]
</IfModule>

如评论中所述,这些指令无法执行任何操作,因为 条件 RewriteCond 指令)永远不会匹配。 HTTP_HOST 服务器变量包含 Host HTTP 请求 header 的值 - 这不包含 URL-path。因此,example.com/blog 永远不会 匹配。

您还把这些指令放在了错误的位置,它们需要在 WordPress 代码块之前,而不是“之后”。通过将此规则放在“Wordpress 指令之后”,除非 /blog 仍然作为物理目录存在,然后(再次)这些指令将永远不会实际执行任何操作,因为它们甚至永远不会被处理(WordPress 代码块捕获请求并将其重写为 front-controller,此时处理有效停止)。如果 /blog 仍然作为物理目录存在,那么前面的 WordPress 代码块应该忽略请求,允许处理此规则。

I can assure you the redirection is done fine. A bit slowly but fine.

可能 表明重定向实际上是由 WordPress 本身执行的,而不是 .htaccess。但是,此“应该”在重定向响应的 HTTP 响应 header 中指明。

要将所有请求从 /blog 子目录重定向到根目录并包含一个额外的 URL 参数只是 one-liner.

例如,之前 WordPress 代码块:

# Redirect "/blog/<anything>" to "/<anything>?sublog=nox"
RewriteRule ^blog(?:$|/(.*)) /?sublog=nox [QSA,R=301,L]

# BEGIN WordPress
:

或者,通过在重定向中包含方案和主机名(正如您所做的那样),确保它始终重定向到 HTTPS 和规范主机名:

RewriteRule ^blog(?:$|/(.*)) https://example.com/?sublog=nox [QSA,R=301,L]

这会将 /blog 重定向到 /?sublog=nox,将 /blog/foo?bar=1 重定向到 /foo?sublog=nox&bar=1(保留初始查询字符串)。

RewriteRule 指令本身检查第一个参数中的 URL-path(即 ^blog(?:$|/(.*)))。正则表达式中额外的“复杂性”是这将同时匹配 /blog(没有尾部斜杠)和 /blog/<anything> 并且仍然保留 substitution 字符串中的斜杠前缀没有重复。

QSA 标志将初始请求中的原始查询字符串(如果有)附加到 替换 字符串的末尾。

补充说明:

  • 规则之前不需要任何额外的条件RewriteCond指令)。
  • 您不需要重复 RewriteEngine On 指令,因为这应该已经出现在文件后面的 WordPress 代码块内。
  • 您不需要 <IfModule> 包装这些指令。这些指令不是 可选的

参考

Apache 官方文档应该是您对此的参考(尽管文档相当简洁并且有些地方缺少示例):