網站 < hsts 的 HSTS 設定>

概觀

元素 <hsts><site> 元素包含屬性,可讓您設定 IIS 10.0 1709 版和更新版本上網站的 HTTP Strict Transport Security (HSTS) 設定。

注意

如果元素 <hsts> 同時在 <siteDefaults> 區段和 <site> 特定月臺的 區段中設定,則區段中的 <site> 組態會用於該網站。

相容性

版本 備註
IIS 10.0 1709 版 元素 <hsts><site> 元素是在 IIS 10.0 1709 版中引進。
IIS 10.0 N/A
IIS 8.5 N/A
IIS 8.0 N/A
IIS 7.5 N/A
IIS 7.0 N/A
IIS 6.0 N/A

安裝程式

元素 <hsts><site> 元素包含在 IIS 10.0 0 1709 版和更新版本的預設安裝中。

作法

沒有使用者介面可讓您 <hsts> 設定 IIS 10.0 0 1709 版元素的 <site> 元素。 For examples of how to configure the <hsts> element of the <site> element programmatically, see the Sample Code section of this document.

組態

屬性

屬性 描述
enabled 選擇性的 Boolean 屬性。

指定是否啟用 HSTS (true) 或停用網站 (false) 。 如果已啟用 HSTS,當 IIS 回復 HTTPS 要求至網站時,就會新增 Strict-Transport-Security HTTP 回應標頭。

預設值是 false
max-age 選擇性 uint 屬性。

指定Strict-Transport-Security HTTP 回應標頭域值中的max-age指示詞。

預設值是 0
includeSubDomains 選擇性的 Boolean 屬性。

指定 IncludeSubDomains 指示詞是否包含在 Strict-Transport-Security HTTP 回應標頭域值中。

注意: 只有在所有子域確實透過 TLS/SSL 提供 HTTP 型服務時,才啟用此屬性。

預設值是 false
preload 選擇性的 Boolean 屬性。

指定 Preload 指示詞是否包含在 Strict-Transport-Security HTTP 回應標頭域值中。

注意: 只有在已提交網站網域以包含在 HSTS 預先載入清單中時,才啟用此屬性。

預設值是 false
redirectHttpToHttps 選擇性的 Boolean 屬性。

指定是否 (true) 啟用 HTTP 至 HTTPS 重新導向,或為網站停用 (false) 。

注意: 啟用 redirectHttpToHttps 會強制執行月臺層級 HTTP 至 HTTPS 重新導向。 當 IIS 重新導向 HTTP 要求時,它會以 「HTTPs」 取代 URI 配置,並忽略埠元件。 請確定重新導向目的地在標準埠 443 上透過 TLS/SSL 提供 HTTP 型服務。

預設值是 false

子元素

無。

組態範例

下列組態範例顯示名為 Contoso 的網站,其 HSTS 已啟用 HTTP 和 HTTPS 系結。 max-age屬性設定為 31536000 秒 (一年) ,讓使用者代理程式會在接收 Strict-Transport-Security標頭欄位之後一年內將主機視為已知 HSTS 主機。 includeSubDomains屬性會設定為true,以指定 HSTS 原則適用于此 HSTS 主機 (contoso.com) 以及例如 www.contoso.commarketing.contoso.com) 的任何子域 (。 最後, redirectHttpToHttps 屬性會設定為 true ,以便將網站的所有 HTTP 要求重新導向至 HTTPS。

<site name="Contoso" id="1">
    <application path="/" applicationPool="Contoso">
        <virtualDirectory path="/" physicalPath="C:\Contoso\Content" />
    </application>
    <bindings>
        <binding protocol="http" bindingInformation="*:80:contoso.com" />
        <binding protocol="https" bindingInformation="*:443:contoso.com" sslFlags="0" />
    </bindings>
    <hsts enabled="true" max-age="31536000" includeSubDomains="true" redirectHttpToHttps="true" />
</site>

範例程式碼

下列程式碼範例會為名為 Contoso 的網站啟用 HSTS,其中包含 HTTP 和 HTTPS 系結。 此範例會將 max-age 屬性設定為 31536000 秒 (年) ,並同時啟用 includeSubDomainsredirectHttpToHttps 屬性。

AppCmd.exe

appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.enabled:True" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.max-age:31536000" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.includeSubDomains:True" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.redirectHttpToHttps:True" /commit:apphost

注意

當您使用 AppCmd.exe 來設定這些設定時,請務必將 認可 參數 apphost 設定為 。 這會將組態設定認可至applicationHost.config檔案中的適當位置區段。

C#

using System;
using System.Text;
using Microsoft.Web.Administration;

internal static class Sample
{
    private static void Main()
    {
        using(ServerManager serverManager = new ServerManager())
        { 
            Configuration config = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
            ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
            
            ConfigurationElement siteElement = FindElement(sitesCollection, "site", "name", @"Contoso");
            if (siteElement == null) throw new InvalidOperationException("Element not found!");

            ConfigurationElement hstsElement = siteElement.GetChildElement("hsts");
            hstsElement["enabled"] = true;
            hstsElement["max-age"] = 31536000;
            hstsElement["includeSubDomains"] = true;
            hstsElement["redirectHttpToHttps"] = true;

            serverManager.CommitChanges();
        }
    }
    
    private static ConfigurationElement FindElement(ConfigurationElementCollection collection, string elementTagName, params string[] keyValues)
    {
        foreach (ConfigurationElement element in collection)
        {
            if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase))
            {
                bool matches = true;
                for (int i = 0; i < keyValues.Length; i += 2)
                {
                    object o = element.GetAttributeValue(keyValues[i]);
                    string value = null;
                    if (o != null)
                    {
                        value = o.ToString();
                    }
    
                    if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase))
                    {
                        matches = false;
                        break;
                    }
                }
                if (matches)
                {
                    return element;
                }
            }
        }
        return null;
    }
}

VB.NET

Imports System
Imports System.Text
Imports Microsoft.Web.Administration

Module Sample

   Sub Main()
      Dim serverManager As ServerManager = New ServerManager
      Dim config As Configuration = serverManager.GetApplicationHostConfiguration
      Dim sitesSection As ConfigurationSection = config.GetSection("system.applicationHost/sites")
      Dim sitesCollection As ConfigurationElementCollection = sitesSection.GetCollection

      Dim siteElement As ConfigurationElement = FindElement(sitesCollection, "site", "name", "Contoso")
      If (siteElement Is Nothing) Then
         Throw New InvalidOperationException("Element not found!")
      End If

      Dim hstsElement As ConfigurationElement = siteElement.GetChildElement("hsts")
      hstsElement("enabled") = True
      hstsElement("max-age") = 31536000
      hstsElement("includeSubDomains") = True
      hstsElement("redirectHttpToHttps") = True

      serverManager.CommitChanges()
   End Sub

   Private Function FindElement(ByVal collection As ConfigurationElementCollection, ByVal elementTagName As String, ByVal ParamArray keyValues() As String) As ConfigurationElement
      For Each element As ConfigurationElement In collection
         If String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase) Then
            Dim matches As Boolean = True
            Dim i As Integer
            For i = 0 To keyValues.Length - 1 Step 2
               Dim o As Object = element.GetAttributeValue(keyValues(i))
               Dim value As String = Nothing
               If (Not (o) Is Nothing) Then
                  value = o.ToString
               End If
               If Not String.Equals(value, keyValues((i + 1)), StringComparison.OrdinalIgnoreCase) Then
                  matches = False
                  Exit For
               End If
            Next
            If matches Then
               Return element
            End If
         End If
      Next
      Return Nothing
   End Function

End Module

JavaScript

var adminManager = new ActiveXObject('Microsoft.ApplicationHost.WritableAdminManager');
adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST";
var sitesSection = adminManager.GetAdminSection("system.applicationHost/sites", "MACHINE/WEBROOT/APPHOST");
var sitesCollection = sitesSection.Collection;

var siteElementPos = FindElement(sitesCollection, "site", ["name", "Contoso"]);
if (siteElementPos == -1) throw "Element not found!";
var siteElement = sitesCollection.Item(siteElementPos);

var hstsElement = siteElement.ChildElements.Item("hsts");
hstsElement.Properties.Item("enabled").Value = true;
hstsElement.Properties.Item("max-age").Value = 31536000;
hstsElement.Properties.Item("includeSubDomains").Value = true;
hstsElement.Properties.Item("redirectHttpToHttps").Value = true;

adminManager.CommitChanges();

function FindElement(collection, elementTagName, valuesToMatch)
{
    for (var i = 0; i < collection.Count; i++)
    {
        var element = collection.Item(i);
        if (element.Name == elementTagName)
        {
            var matches = true;
            for (var iVal = 0; iVal < valuesToMatch.length; iVal += 2)
            {
                var property = element.GetPropertyByName(valuesToMatch[iVal]);
                var value = property.Value;
                if (value != null)
                {
                    value = value.toString();
                }
                if (value != valuesToMatch[iVal + 1])
                {
                    matches = false;
                    break;
                }
            }
            if (matches)
            {
                return i;
            }
        }
    }
    
    return -1;
}

VBScript

Set adminManager = WScript.CreateObject("Microsoft.ApplicationHost.WritableAdminManager")
adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST"
Set sitesSection = adminManager.GetAdminSection("system.applicationHost/sites", "MACHINE/WEBROOT/APPHOST")
Set sitesCollection = sitesSection.Collection
siteElementPos = FindElement(sitesCollection, "site", Array("name", "Contoso"))

If siteElementPos = -1 Then
   WScript.Echo "Element not found!"
   WScript.Quit
End If

Set siteElement = sitesCollection.Item(siteElementPos)
Set hstsElement = siteElement.ChildElements.Item("hsts")
hstsElement.Properties.Item("enabled").Value = True
hstsElement.Properties.Item("max-age").Value = 31536000
hstsElement.Properties.Item("includeSubDomains").Value = True
hstsElement.Properties.Item("redirectHttpToHttps").Value = True

adminManager.CommitChanges()

Function FindElement(collection, elementTagName, valuesToMatch)
   For i = 0 To CInt(collection.Count) - 1
      Set element = collection.Item(i)
      If element.Name = elementTagName Then
         matches = True
         For iVal = 0 To UBound(valuesToMatch) Step 2
            Set property = element.GetPropertyByName(valuesToMatch(iVal))
            value = property.Value
            If Not IsNull(value) Then
               value = CStr(value)
            End If
            If Not value = CStr(valuesToMatch(iVal + 1)) Then
               matches = False
               Exit For
            End If
         Next
         If matches Then
            Exit For
         End If
      End If
   Next
   If matches Then
      FindElement = i
   Else
      FindElement = -1
   End If
End Function

IISAdministration PowerShell Cmdlet

Import-Module IISAdministration
Reset-IISServerManager -Confirm:$false
Start-IISCommitDelay

$sitesCollection = Get-IISConfigSection -SectionPath "system.applicationHost/sites" | Get-IISConfigCollection
$siteElement = Get-IISConfigCollectionElement -ConfigCollection $sitesCollection -ConfigAttribute @{"name"="Contoso"}
$hstsElement = Get-IISConfigElement -ConfigElement $siteElement -ChildElementName "hsts"
Set-IISConfigAttributeValue -ConfigElement $hstsElement -AttributeName "enabled" -AttributeValue $true
Set-IISConfigAttributeValue -ConfigElement $hstsElement -AttributeName "max-age" -AttributeValue 31536000
Set-IISConfigAttributeValue -ConfigElement $hstsElement -AttributeName "includeSubDomains" -AttributeValue $true
Set-IISConfigAttributeValue -ConfigElement $hstsElement -AttributeName "redirectHttpToHttps" -AttributeValue $true

Stop-IISCommitDelay
Remove-Module IISAdministration