使用 IIS 将所有 URL 重定向到 HTTPS/WWW 版本

Redirect all URLs to HTTPS/WWW versions using IIS

我有一个网站,刚刚购买了 SSL。我希望所有 URL 都重定向到它们的 HTTPS/WWW 版本。例如:

1. http://mywebsite.com       ->   https://www.mywebsite.com
2. https://mywebsite.com      ->   https://www.mywebsite.com
3. http://www.mywebsite.com   ->   https://www.mywebsite.com
4. https://www.mywebsite.com  ->   [No redirect needed]

我已经尝试了一些解决方案: and 来自标记为答案的方法。但是对于案例 2,几乎所有的答案 return“Not Found. HTTP Error 404”,即 https://mywebsite.com 没有重定向到 https://www.mywebsite.com,而是 returned 404。

已经尝试过的解决方案:

1.

<rule name="Redirect top domains with non-www to www" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^([^\.]+)\.([^\.]+)$" />
      </conditions>
      <action type="Redirect" url="https://www.{HTTP_HOST}/{R:1}" redirectType="Permanent" />
      <serverVariables>
        <set name="Redirect" value="false" />
      </serverVariables>
</rule>
<rule name="Force HTTPS" enabled="true" stopProcessing="true">
      <match url="(.*)" ignoreCase="false" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTPS}" pattern="off" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
 </rule>

2.

<rule name="Force WWW and SSL" enabled="true" stopProcessing="true">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAny">
      <add input="{HTTP_HOST}" pattern="^[^www]" />
      <add input="{HTTPS}" pattern="off" />
  </conditions>
  <action type="Redirect" url="https://www.zzz.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>

好像其他人也有这个问题。但是我找不到合适的解决方案。

问题出在 IIS 的 Site Bindings 部分。 https://mywebsite.com 没有记录。我添加了这条记录,问题中的解决方案有效。有关此功能的更多信息,请访问 this page.