SSL证书在配置HSTS(HTTP严格传输安全)可以有效强制客户端使用HTTPS连接,防止中间人攻击。以下是具体配置方法和注意事项:

一、基础配置方法

1.  通过HTTP响应头配置

http

Strict-Transport-Security:  max-age=31536000;  includeSubDomains;  preload

max-age:  有效期(秒),建议至少6个月

includeSubDomains:  包含所有子域名

preload:  申请加入浏览器预加载列表

2.  主流服务器配置示例

Nginx配置

nginx

add_header  Strict-Transport-Security  "max-age=31536000;  includeSubDomains;  preload"  always;

Apache配置

apache

<VirtualHost  *:443>

        Header  always  set  Strict-Transport-Security  "max-age=31536000;  includeSubDomains;  preload"

</VirtualHost>

Express.js  (Node.js)

javascript

app.use(helmet.hsts({

        maxAge:  31536000,

        includeSubDomains:  true,

        preload:  true

}));

二、分阶段部署建议

第一阶段:测试阶段

http

Strict-Transport-Security:  max-age=300;  includeSubDomains

设置较短的max-age(如5分钟),验证不影响正常业务。

第二阶段:生产部署

http

Strict-Transport-Security:  max-age=31536000;  includeSubDomains

确认无误后,延长至1年。

第三阶段:预加载申请

http

Strict-Transport-Security:  max-age=31536000;  includeSubDomains;  preload

通过  hstspreload.org  提交域名到预加载列表。

三、关键注意事项

确保HTTPS完全可用

所有HTTP请求必须能正确重定向到HTTPS

证书必须有效且受信任

防止锁死

nginx

先配置HTTP到HTTPS的重定向

server  {

        listen  80;

        server_name  example.com;

        return  301  https://$server_name$request_uri;

}

子域名处理

使用includeSubDomains前,确保所有子域名都支持HTTPS

特别是API、CDN、第三方服务等

四、验证和测试

1.  检查HSTS头

bash

curl  -I  https://yourdomain.com

2.  在线检测工具

SecurityHeaders.com

HSTS  Preload  List  Check

3.  浏览器开发者工具

在Network标签页查看响应头是否包含HSTS。

五、撤销和调试

如果需要撤销HSTS:

设置max-age=0清除HSTS设置

浏览器需要访问一次该设置才能清除

或在浏览器设置中手动清除HSTS记录

六、完整配置示例(Nginx)

nginx

server  {

        listen  80;

        server_name  example.com  www.example.com;

        return  301  https://$server_name$request_uri;

}


server  {

        listen  443  ssl  http2;

        server_name  example.com  www.example.com;

        

        ssl_certificate  /path/to/cert.pem;

        ssl_certificate_key  /path/to/key.pem;

        

        HSTS配置

        add_header  Strict-Transport-Security  "max-age=31536000;  includeSubDomains;  preload"  always;

        

        其他安全头

        add_header  X-Frame-Options  DENY;

        add_header  X-Content-Type-Options  nosniff;

        add_header  X-XSS-Protection  "1;  mode=block";

}

配置完成后,建议在staging环境充分测试,再逐步部署SSL证书到生产环境。