2011-09-10 22 views

回答

31

如果你想讓它與任何主機名(沒有硬編碼到規則)的工作,你會想要做這樣的事情:

<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」也會將任何查詢字符串附加到重定向(如果存在)。請記住,如果存在的話,任何URL哈希值都將在這個過程中丟失,因爲這些哈希值不會傳遞給服務器。

+0

我從來沒有對第一個答案中的硬編碼片段感到興奮,很高興我終於可以標記在這個問題上的答案。 –

+3

如果有人進入https,該怎麼辦?你不想自動將它們重定向到http,是嗎? – jedmao

+0

@mrjedmao好點!我會研究它:) –

5

以下一個應該工作:

<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> 
-1

要進行重定向,將兩個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> 
2

IIS將自動爲您完成以下事項:

選擇網站> URL重寫>新規則>規範主機姓名:)

+0

最佳答案當然。 –