URL重写规则在.NET中强制www,但忽略http(s)

问题描述:

我期待在我的web.config文件中设置重写规则,强制URL使用'www'子域。这是像这样做:URL重写规则在.NET中强制www,但忽略http(s)

<rules> 
    <rule name="Add WWW" stopProcessing="true"> 
    <match url="^(.*)$" /> 
    <conditions> 
     <add input="{HTTP_HOST}" pattern="^(?!www\.)(.*)$" /> 
    </conditions> 
    <action type="Redirect" url="http://www.{C:0}{PATH_INFO}" redirectType="Permanent" /> 
</rule> 

然而,在项目运行在多个领域,其中一些使用SSL和一些不多个网站。

上面的代码硬编码为http://进入重定向。我所要做的就是抽象出这样的内容,即http或https协议在重定向期间保持不变,而不用硬编码。

所期望的结果的一些实例是:

非常感谢。

我发现了一个reference,它解释了这样做的一种方法。它使用重写键/值对作为动作url中的“变量”,因为(据我所知),目前没有办法将协议作为规则中的本地变量来获取。

该规则已被修改如下,这应该要做的事需要什么:

<rewrite> 
    <rules> 
      <rule name="Add www maintain https" stopProcessing="true"> 
      <match url="^(.*)$" /> 
      <conditions> 
      <add input="{HTTP_HOST}" pattern="^(?!www\.)(.*)$" /> 
      </conditions> 
      <action type="Redirect" url="{MapSSL:{HTTPS}}www.{C:0}{PATH_INFO}" redirectType="Permanent" /> 
     </rule> 
    </rules> 
    <rewriteMaps> 
     <rewriteMap name="MapSSL" defaultValue="http://"> 
      <add key="ON" value="https://" /> 
      <add key="OFF" value="http://" /> 
     </rewriteMap> 
    </rewriteMaps> 
</rewrite> 

还有另一个reference其中包括本之间的替代方法来达到同样的事情。