日期:2019-08-23  浏览次数:3544 次

由于谷歌宣布他们将对安全网站进行排名提升,我最近不得不将一些网站转换为HTTPS / SSL。

我正在运行带有IIS 7和.NET 4.5的Windows 2008服务器,我使用IIS URL Rewrite 2.0为从http到https的所有请求设置301重定向,您可以使用Microsoft Web Platform Installer安装IIS URL Rewrite 2.0,它的安装速度仅为6.1mb。这是我添加到web.config文件的<system.webServer>部分的规则:

IIS URL重写规则为301将HTTP重定向到HTTPS

<rewrite>
  <rules>
    <rule name="Redirect everything to http:// on www domain" patternSyntax="Wildcard" stopProcessing="true">
      <match url="*" />
      <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="www.[DOMAIN].com" negate="true" />
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="http://www.[DOMAIN].com/{R:0}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>


设置从http到https的自动重定向后,您可能会开始看到有关“ 不安全内容 ”或“ 混合内容 ”的浏览器警告,并且某些内容可能会被阻止而不会显示,这是因为您的html中的某些外部内容引用仍在使用一个不安全的“http://”网址。外部内容可以包括脚本引用,css样式表,图像,视频等。

有几种方法可以解决此问题:

  1. 您可以手动更新html中的所有外部内容引用以使用https(例如脚本,CSS,图像,视频等)。
  2. 如果您的部分/全部html由CMS管理且不受控制,那么您可能需要动态更新外部内容引用以在将html发送到浏览器之前使用https
 

如果您需要使用选项2(就像我一样),那么您可以再次使用IIS URL Rewrite 2.0来动态更新html中的所有外部内容引用,以便在将其发送到浏览器之前使用HTTPS / SSL。

我使用以下出站规则在所有脚本,链接(css),img和视频标记中将“http://”替换为“https://”。视频标记未包含在URL重写的预定义标记中,因此我将其添加为自定义标记,您可以扩展规则以包含您需要的任何其他标记。

IIS URL重写规则以强制外部内容引用使用HTTPS / SSL

<rewrite>

  ...

  <outboundRules>
    <rule name="Rewrite external references to use HTTPS" preCondition="IsHTML">
      <match filterByTags="Script, Link, Img, CustomTags" customTags="HTML5Tags" pattern="^http://(.*)$" />
      <action type="Rewrite" value="http://{R:1}" />
    </rule>
    <preConditions>
      <preCondition name="IsHTML">
        <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
      </preCondition>
    </preConditions>
    <customTags>
      <tags name="HTML5Tags">
        <tag name="Video" attribute="src" />
      </tags>
    </customTags>
  </outboundRules>
</rewrite>

这适用于在IIS 7或更高版本上运行的任何网站,包括使用ASP.NET MVC3,MVC4,MVC5和Web窗体开发的网站。