.htaccess If/Else 语句不适用于 HTTP_HOST

.htaccess If/Else statement doesn't work with HTTP_HOST

这是我的 .htaccess 文件:

 RewriteEngine On

 <If "%{HTTP_HOST} == '<myHost>'">
   RewriteRule ^$ <url> [R=301,L]
 </If>
 <Else>
  RewriteRule ^$ <another_url> [R=301,L]
 </Else>

但它不起作用,似乎 <If> 语句被忽略了。我还在 PHP 中对 $_SERVER['HTTP_HOST'] 进行了回显,在那里我得到了我期望的值。此外,如果我删除 If/Else 语句,RewriteRule 会正常工作。

我在 Apache/2.4.38 (Debian)

中使用 Azure Webapp

ifelse 块中,您可以使用 RedirectMatch 指令,因为它与它一起工作。 RewriteRule 不起作用,因为它覆盖并与 IF/ELSE.

冲突
 RewriteEngine On

 <If "%{HTTP_HOST} == '<myHost>'">
 RedirectMatch 301 ^/$ https://example.com
 </If>
 <Else>
 RedirectMatch ^/$ https://example2.com
 </Else>

<If> 语句不会被忽略。 “问题”是当在 <If> 表达式中使用时 RewriteRule 模式 匹配绝对文件系统路径,而不是请求的 URL-路径你在期待。

<If>块改变了处理的顺序。 <If> blocks are merged very late,在 .htaccess 文件被正常处理之后,似乎在请求被重新映射回文件系统之后(即在目录前缀被添加回来之后)。

考虑到这一点,您可以将规则更改为以下内容以使其生效:

<If "%{HTTP_HOST} == '<myHost>'">
  RewriteRule ^/file/path/to/document-root/$ <url> [R=301,L]
</If>
<Else>
  RewriteRule ^/file/path/to/document-root/$ <another_url> [R=301,L]
</Else>

其中 /file/path/to/document-root/ 是文档根目录的绝对文件系统路径(URL-path / 映射到的位置)。

或者,在条件中使用 REQUEST_URI 服务器变量检查 URL 路径。例如:

<If "%{HTTP_HOST} == '<myHost>'">
  RewriteCond %{REQUEST_URI} =/
  RewriteRule ^ <url> [R=301,L]
</If>
<Else>
  RewriteCond %{REQUEST_URI} =/
  RewriteRule ^ <another_url> [R=301,L]
</Else>

或者,检查 <If>(和 <ElseIf>)表达式中的 REQUEST_URI 变量。在 Apache 2.4.26+ 上,您可以嵌套表达式。例如:

<If "%{REQUEST_URI} == '/'">
  <If "%{HTTP_HOST} == '<myHost>'">
    RewriteRule ^ <url> [R=301,L]
  </If>
  <Else>
    RewriteRule ^ <another_url> [R=301,L]
  </Else>
</If>

或者,按照@AmitVerma 的回答中的建议,在 <If> 表达式中使用 mod_alias RedirectMatch 指令。 mod_alias RedirectMatch(和 Redirect)指令总是引用请求的(root-relative)URL-path,无论上下文如何,所以你不会得到这种歧义mod_rewrite.

或者,直接使用mod_rewrite即可,这里不需要<If>/<Else>表达式。例如:

RewriteCond %{HTTP_HOST} =<myHost>
RewriteRule ^$ <url> [R=301,L]
RewriteRule ^$ <another_url> [R=301,L]