运行 second 在执行第一个规则后重写条件和规则

run second Rewrite condition and rule after the first rule is executed

我的 .htaccess 文件是:

# remove "www"
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]

# add trailing slash "/"
RewriteCond %{HTTP_HOST} ^(www\.)?example.com$
RewriteRule ^(.*(?:^|/)[^/\.]+)$ / [R=301,L]

# other rules needed
RewriteCond %{HTTP_HOST} ^(www\.)?example.com$
RewriteRule ^old-link/$ https://example.com/new-link/ [R=301,L]

我的目标是http://www.example.com/something-after redirect to https://example.com/something-after 之后我想在末尾添加“/”:https://example.com/something-after/

但是,我已经在在线测试器中对此进行了测试,它说“测试已停止,使用不同的主机将导致重定向”第一条规则和因此,第二条规则从未被满足。

I have tested this in a online tester and it says that the "The tests are stopped, using a different host will cause a redirect" on the first rule and for this reason the second rule is never met.

大多数在线测试人员只通过指令一次(在单个请求中)。在真实服务器上,可能会发生多次传递(和多次请求)。

这些指令并没有真正的问题,只是它可能会触发多个重定向。例如。 https://www.example.com/foo 的请求将触发 两个 外部重定向。第一个到 https://example.com/foo(删除 www),第二个到 https://example.com/foo/(附加斜线)。在极端情况下,请求 https://www.example.com/old-link(没有尾部斜杠)将触发 三个 外部重定向。

可以通过简单地重新排序规则并在重定向中明确包含方案+主机名以附加尾部斜杠(当前是第二条规则)来避免这些多重重定向,就像您在其他两个规则中所做的那样。此外,允许在 /old-link/ 规则上使用可选的尾部斜杠。

例如:

# Specific redirects
RewriteCond %{HTTP_HOST} ^(?:www\.)?(example\.com) [NC]
RewriteRule ^old-link/?$ https://%1/new-link/ [R=301,L]

# Add trailing slash "/"
RewriteCond %{HTTP_HOST} ^(?:www\.)?(example\.com) [NC]
RewriteRule ^(.*(?:^|/)[^/.]+)$ https://%1// [R=301,L]

# Remove "www"
RewriteCond %{HTTP_HOST} ^www\.(example\.com) [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

现在,只需要处理一条规则。删除 www、附加斜杠和重定向 /old-link 都由单个规则处理。

其他小改动:

  • 我在 CondPattern 中捕获了域,并在 substitution 字符串中使用了 %1 反向引用。这只是省去了在 替换 字符串中显式重复域名的麻烦。
  • CondPattern 中删除了 $(end-of-string 锚点)以允许以点结尾的 FQDN。
  • RewriteCond 指令添加了 NC 标志。 (机器人可能会请求混合大小写 Host header。)
  • 不需要 backslash-escape 正则表达式字符 class 内的文字点。点在这里没有特殊意义。

但是,这里的另一个问题是您目前没有 HTTP 到 HTTPS 的重定向。您可以将其添加为 last 规则:

# Redirect HTTP to HTTPS
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

这只是一个标准的 HTTP 到 HTTPS 重定向,假设 SSL 证书直接安装在应用程序服务器上。

通过放置规则 last,您只需检查 example.com(而不是 www.example.com),因为请求必须已经规范化(以根据前面的规则(如果需要)删除 www 子域)。