如何在 web.config 中将所有流量重定向到 https 和非 www?

How to redirect all traffic to https & non-www in web.config?

我正在使用 SSL 证书和 IIS。在我的 web.config 中,我想按以下顺序重定向所有网站流量:

  1. 所有 http --> https
  2. 所有 www --> 非 www

您想使用 redirect module 来执行此操作。这会在请求进入服务器时拦截它并根据您的指示进行更改。

这是将所有重定向到 https 的操作:

<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />

这是将 www 重定向到非 www 的方法:

<conditions> <add input=”{HTTP_HOST}” pattern=”^example\.com$” negate=”true” /> </conditions> <action type=”Redirect” url=”http://example.com/{R:1}” />

当您在搜索中同时包含 "web.config" 和 "redirect" 时,网络和 Whosebug 上有很多文章。

确保在设置规则时只在最终规则上使用 stopProcessing="true"。如果出现在第一条规则中,那么第二条规则将永远不会执行。

我找到了答案

 <system.webServer>


  <rewrite>
   <rules>
     <clear />

     <rule name="NonWwwRedirect"  stopProcessing="true"> 
    <match url="(.*)" /> 
    <conditions> 
        <add input="{HTTP_HOST}" pattern="^www.yoursit\.com$" /> 
    </conditions> 
    <action type="Redirect" url="http://yoursite.com/{R:1}" /> 
</rule> 
     <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 />