最近客戶一個網站升級至HTTPS協議訪問,但是為了用戶輸入,客戶要求當用戶輸入的是HTTP協議時,能自動定向到HTTPS,類似百度網站,當你輸入www.baidu.com並回車后,地址欄自動變成了https://www.baidu.com。
以前步驟簡要介紹了如何實現該功能。
1)下載並安裝Microsoft URL 重寫模塊
https://www.microsoft.com/zh-CN/download/details.aspx?id=7435
備注:根據不同的系統,不同的語言選擇。
我的機器是英文版的,所以以下截圖基本都為英文。
2) 站點綁定以下兩種協議:
注意:默認的https端口號為443, 因為我本機這個端口已經被利用,所以此處以449演示。
3)站點的SSL設置,確保“Require SSL”未選中。
3)如果是ASP.NET站點,則直接在Web.config文件中添加以下配置節,作為<configuration>的子元素放在文件末尾即可。
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect to https" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
<add input="{HTTPS_HOST}" pattern="^(localhost)" negate="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}:449/{R:1}" redirectType="SeeOther" />
</rule>
</rules>
</rewrite>
</system.webServer>
注意:當你使用默認HTTPS端口時,上面的端口號449就不需要了,直接為https://{HTTP_HOST}/{R:1}
上面的配置也可以直接在IIS中的URL Write中手動添加,完成后大致如下:
Web.config配置:
<?xml version="1.0" encoding="utf-8"?> <!-- 有關如何配置 ASP.NET 應用程序的詳細信息,請訪問 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> <system.webServer> <rewrite> <rules> <rule name="Redirect to https" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTPS}" pattern="^OFF$" /> <add input="{HTTPS_HOST}" pattern="^(localhost)" negate="true" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}:449/{R:1}" redirectType="SeeOther" /> </rule> </rules> </rewrite> </system.webServer> </configuration>