Asp.net

Microsoft 重寫模組 - 在 url 上強制 www 或從 url 中刪除 www

  • January 12, 2016

我有一個與 Windows Server 2008 和 IIS7.5 共享的託管計劃,並且安裝並啟用了 Microsoft 重寫模組。

<rewrite>
   <rules>
       <rule name="myRule" patternSyntax="Wildcard">
           <!--Rewriting code-->
       </rule>
   </rules>
</rewrite>

那麼,如何使用 Microsoft 重寫模組將 mydomain.com/everywhere-in-site/my-page.html 重定向到 www.mydomain.com/everywhere-in-site/my-page.html

如果我想將 www.mydomain.com/everywhere-in-site/my-page.html 重定向到 mydomain.com/everywhere-in-site/my-page.html 怎麼辦?

要從域中刪除 www 並重定向到“裸域”,您可以像以下程式碼片段一樣進行操作:

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

反過來(如果您願意的話)將非 www 重定向到帶有 www 的:

<rewrite>
 <rules>
   <rule name="Add WWW prefix" stopProcessing="true">
     <match url="(.*)" ignoreCase="true" />
     <conditions>
       <add input="{HTTP_HOST}" pattern="^yourdomain\.com$" />
     </conditions>
     <action type="Redirect" url="http://www.yourdomain.com/{R:0}" redirectType="Permanent" />
   </rule>
 </rules>
</rewrite>

redirectType="Permanent"當然是可選的,但對於 SEO 和大多數情況,我會推薦它。

另請參閱這些 SO 問題/答案:

引用自:https://stackoverflow.com/questions/10153670