Iis 7 使用IIS URL重写从地址中删除www的正确方法

Iis 7 使用IIS URL重写从地址中删除www的正确方法,iis-7,iis-7.5,url-rewriting,Iis 7,Iis 7.5,Url Rewriting,使用IIS url重写从url中删除www子域的最佳方法是什么?以下方法应该有效: <system.webServer> <rewrite> <rules> <rule name="Remove WWW" stopProcessing="true"> <match url="^(.*)$" /> <conditions> <add input=

使用IIS url重写从url中删除www子域的最佳方法是什么?

以下方法应该有效:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Remove WWW" stopProcessing="true">
        <match url="^(.*)$" />
        <conditions>
          <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
        </conditions>
        <action type="Redirect" url="http://www.example.com{PATH_INFO}" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

如果您想让它与任何主机名一起工作(而不是将其硬编码到规则中),您需要执行以下操作:

<rule name="Remove www" stopProcessing="true">
  <match url="(.*)" ignoreCase="true" />
  <conditions logicalGrouping="MatchAll">
    <add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
  </conditions>
  <action type="Redirect" url="http://{C:1}/{R:0}" appendQueryString="true" redirectType="Permanent" />
</rule>


在重定向操作中,{C:1}包含条件中的第二个捕获组,{R:0}包含规则中的任何内容(路径)。appendQueryString=“true”还会将任何querystring附加到重定向(如果存在)。但是请记住,任何url哈希(如果存在)都将在过程中丢失,因为这些哈希不会传递到服务器。

要执行适用于http和https的重定向,可以使用以下命令

    <rewrite>
        <rules>
            <rule name="Lose the www" enabled="true" stopProcessing="true">
                <match url="(.*)" ignoreCase="true"/>
                <conditions logicalGrouping="MatchAll">
                    <add input="{HTTP_HOST}" pattern="^www\.(.*)$"/>                    
                </conditions>
                <action type="Redirect" redirectType="Permanent" url="{SchemeMap:{HTTPS}}://{C:1}/{R:1}" appendQueryString="true" />
            </rule>
        </rules>
        <rewriteMaps>
            <rewriteMap name="SchemeMap">
                <add key="on" value="https" />
                <add key="off" value="http" />
            </rewriteMap>
        </rewriteMaps>
    </rewrite>

IIS会自动为您执行以下操作:


选择站点>URL重写>新规则>规范主机名:)

我从来没有对第一个答案中的硬编码片段感到兴奋,很高兴我终于可以标记出这个问题的答案。如果有人使用https怎么办?您不想自动将它们重定向到http,是吗?也许您可以将
http://
替换为
/
,它将按照您想要的方式工作。@mrjedmao不,您不能使用协议相关url作为基本url。重写将重写请求,而不是标记。当浏览器在标记中看到href=“//google.com”时,它将查看基本url(地址栏中的url)并使用相同的协议。请求本身将分别包含http://或https://。尝试在浏览器中键入//google.com。您也可以使用IIS重写来修改标记,但这需要一个输出重写规则。Mads Kristensen为此提供了一个很好的配置示例,它也是协议无关的(支持HTTPS):最好的答案是肯定的。您在操作中使用了www吗?