IIS/Azure web.config 文件的简单规则将流量重定向到非 www HTTPS

Simple rule(s) for IIS/Azure web.config file to redirect traffic to non-www HTTPS

我的目标是在 IIS/Azure 的 web.config 文件中添加规则以成功重定向以下客户端请求示例:

HTTPS 重定向:

无 www 和 HTTPS 重定向:

无 www,HTTPS 重定向和维护路径:

这是我目前所拥有的,仅实现了第 1 点和第 2 点。如果访问者直接登陆子页面,他们不会被重定向到非 www,也不会被重定向到 HTTPS。

    <rule name="Redirect to https">
      <match url="(.*)"/>
      <conditions>
        <add input="{HTTPS}" pattern="Off"/>
        <add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"/>
    </rule>
    <rule name="Canonical Hostname" stopProcessing="false">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
      </conditions>
      <action type="Redirect" url="https://{C:2}{REQUEST_URI}" redirectType="Permanent" />
    </rule>

我已经用尽了多个搜索结果页面和多个 Whosebug 问题,但没有任何运气 - 他们都承诺能够实现第三点(重定向到非 www,HTTPS 页面 保持路径)但他们没有为我工作。

感谢您花时间阅读本文!

我发现了这个问题,部分原因在于我提出问题的方式(抱歉,Whosebugers!)。

问题出在规则的排序上。我已将以下(新)规则按以下顺序放在我的规则部分的顶部,以供将来遇到此问题的人使用。现在,它正在重定向到 HTTPS,没有 www,并保持客户端请求的路径。

  <rule name="Canonical Hostname" stopProcessing="false">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
      <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
    </conditions>
    <action type="Redirect" url="http://{C:2}{REQUEST_URI}" redirectType="Permanent" />
  </rule>
  <rule name="Force HTTPS" enabled="true">
    <match url="(.*)" ignoreCase="false" />
    <conditions>
      <add input="{HTTPS}" pattern="off" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
  </rule>