1. HTTPS 与证书概述
HTTPS(HTTP Secure)通过 SSL/TLS 协议加密客户端与服务器之间的通信,防止数据在传输过程中被窃听或篡改。
证书类型
| 类型 | 适用场景 | 获取方式 |
|---|---|---|
| 自签名证书 | 测试环境、内部系统 | IIS 管理器创建 |
| 企业 CA 证书 | 企业内部、域环境 | Active Directory 证书服务 |
| 公共 CA 证书 | 面向公网的生产环境 | Let's Encrypt、DigiCert 等 |
⚠️ 生产环境警告
生产环境应使用受信任的 CA 签发的证书,而非自签名证书。自签名证书会在浏览器中显示"不安全"警告。
2. 创建自签名证书
1
打开IIS 管理器 → 选择服务器节点
2
双击"服务器证书" → 右侧"创建自签名证书"
3
填写证书名称:www.iehang.cn
4
证书存储:选择"个人"(默认)→ 点击"确定"
PowerShell - 创建证书
# 创建自签名证书(New-SelfSignedCertificate 需要 PowerShell 5.1+)
$cert = New-SelfSignedCertificate `
-DnsName "www.iehang.cn" `
-CertStoreLocation "Cert:\LocalMachine\My" `
-FriendlyName "IIS HTTPS Certificate"
# 查看证书指纹
$cert.Thumbprint
# 导出证书(可选,用于客户端信任)
Export-Certificate -Cert $cert `
-FilePath "C:\Temp\iis_cert.cer" `
-Type CERT
3. 配置 HTTPS 绑定
1
选择网站"MyWebSite" → 右侧"绑定"
2
点击"添加" → 类型选择 https
3
选择:
- IP 地址:全部未分配
- 端口:443
- SSL 证书:选择
www.iehang.cn
4
点击"确定" → 测试访问 https://www.iehang.cn
PowerShell - HTTPS 绑定
# 添加 HTTPS 绑定
New-WebBinding -Name "MyWebSite" `
-Protocol "https" `
-Port 443
# 获取证书并绑定
$cert = Get-ChildItem "Cert:\LocalMachine\My" | Where-Object { $_.Subject -match "www.iehang.cn" }
$binding = Get-WebBinding -Name "MyWebSite" -Protocol "https"
$binding.AddSslCertificate($cert.GetCertHashString(), "My")
# 验证 HTTPS 绑定
Get-WebBinding -Name "MyWebSite" | Format-Table Protocol, Port, HostHeader -AutoSize
4. 强制 HTTPS 重定向
PowerShell - URL 重写规则
# 安装 URL Rewrite 模块(需下载)
# https://www.iis.net/downloads/microsoft/url-rewrite
# 配置 web.config 强制 HTTPS
$webConfig = @"
<configuration>
<system.webServer>
<rewrite>
<rules>
<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>
</rules>
</rewrite>
</system.webServer>
</configuration>
"@
$webConfig | Out-File -FilePath "D:\Websites\MyWebSite\web.config" -Encoding utf8
5. 常见问题
Q1:浏览器显示"证书不受信任"
自签名证书默认不受客户端信任。测试环境可在客户端安装证书到"受信任的根证书颁发机构"存储。生产环境应使用公共 CA 签发的证书。
Q2:如何申请免费的 SSL 证书
推荐使用 Let's Encrypt,提供免费且受信任的 DV 证书。可使用 win-acme 工具自动申请和续期:https://www.win-acme.com/
Q3:多域名共用一个证书
申请多域名证书(SAN Certificate),在证书中添加多个 Subject Alternative Name。IIS 绑定时同一证书可被多个站点使用。