如何通过 web.config 将 http 重定向到 https 并将 www 重定向到非 www?

How to redirect http to https and www to non-www via web.config?

我想使用 web.config 将我的 asp.net 站点上的所有请求重定向到非 www 的 https://。即:

http://
http://www
https://www

应该都去

https://

到目前为止我的 web.config:

<system.webServer>
...
 <rewrite>
   <rules>
     <clear />
     <rule name="Redirect to https" stopProcessing="true">
       <match url=".*" />
       <conditions>
         <add input="{HTTPS}" pattern="off" ignoreCase="true" />
       </conditions>
       <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
     </rule>
   </rules>
 </rewrite>
</system.webServer>

上面的代码片段负责重定向这两个:

http://
http://www

但我遗漏了最后一个,即:

https://www  --->  https://

怎么做?

您需要添加第二条规则:

<rule name="NonWwwRedirect"  stopProcessing="true"> 
    <match url="(.*)" /> 
    <conditions> 
        <add input="{HTTP_HOST}" pattern="^www.sitename\.com$" /> 
    </conditions> 
    <action type="Redirect" url="http://sitename.com/{R:1}" /> 
</rule> 

您只需要将sitename.com替换为您的域名

这是一条对我有用的通用规则:

<rule name="Force non-WWW" enabled="true" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
    </conditions>
    <action type="Redirect" url="http://{C:2}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>