[英]IIS URL Rewriting: Enforce canonical hostname & HTTP to HTTPS redirect
我在web.config文件中使用這兩個規則:
<rule name="Enforce canonical hostname" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" negate="true" pattern="^www\.example\.com$" />
</conditions>
<action type="Redirect" url="https://www.example.com/{R:1}" redirectType="Permanent" />
</rule>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
</rule>
通過這兩個規則,我得到以下重定向工作:
不確定你是否還在尋找答案,但現在就去了。 經過一些搜索和反復試驗后,我發現了以下規則的成功。 我遇到的大多數示例在模式匹配方面都不必要地復雜,並引入了阻止規則按預期工作的其他變量。 以下規則可以應用於任何網站,沒有任何硬編碼,因此它應該始終是一個直接的復制粘貼工作:
<rule name="Redirect to WWW" stopProcessing="true" >
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^www\." negate="true"/>
</conditions>
<action type="Redirect" url="https://www.{HTTP_HOST}{HTTP_URL}" redirectType="Permanent" appendQueryString="false" />
</rule>
<rule name="Redirect to HTTPS">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="OFF"/>
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{HTTP_URL}" redirectType="Permanent" appendQueryString="false" />
</rule>
有兩點需要注意:redirectType =“Permanent”將導致規則被應用,直到瀏覽器的歷史記錄/緩存被清空為止; 這應該是一件好事,因為瀏覽器將繼續進行工作。 此外,appendQueryString =“false”是必要的,因為{HTTP_URL}服務器變量已經包含完整的查詢字符串; 默認情況下,該選項為“true”,這將導致重復的查詢字符串。
如果這是為了任何人的利益,這里只有一條規則獲得同樣的東西:
<rule name="Redirect HTTP to HTTPS and non-WWW to WWW" stopProcessing="true">
<match url="(.*)"/>
<conditions trackAllCaptures="false" logicalGrouping="MatchAny"> <!-- match non-HTTPS or non-WWW -->
<add input="{HTTPS}" pattern="^OFF$"/> <!-- if connection not secure -->
<add input="{HTTP_HOST}" matchType="Pattern" ignoreCase="true" pattern="^example\.com$" /><!-- domain is not canonical -->
</conditions>
<action type="Redirect" url="https://www.example.com{HTTP_URL}" redirectType="Permanent" appendQueryString="false"/>
</rule>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.