插件窝 干货文章 nginx是如何配置HSTS的

nginx是如何配置HSTS的

配置 Nginx HSTS includeSubDomain 65    来源:    2025-04-25

Nginx 配置 HSTS (HTTP Strict Transport Security) 指南

HSTS 是一种安全策略机制,可以强制客户端(如浏览器)只通过 HTTPS 与服务器建立连接,防止 SSL 剥离攻击。以下是 Nginx 配置 HSTS 的方法:

基本配置

在 Nginx 的 HTTPS 服务器配置中添加以下指令:

server {
    listen 443 ssl;
    server_name example.com;

    # SSL证书配置
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    # 启用HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # 其他配置...
}

参数说明

  • max-age=31536000:HSTS 策略的有效期(单位:秒),这里设置为1年
  • includeSubDomains:可选参数,表示此策略也适用于所有子域名
  • preload:可选参数,表示希望被加入浏览器的预加载列表(需谨慎使用)

推荐配置

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

注意事项

  1. 仅适用于 HTTPS:HSTS 头只能在 HTTPS 响应中设置,HTTP 响应中设置无效

  2. 测试阶段建议:初次部署时,可以先用较小的 max-age 值测试:

    add_header Strict-Transport-Security "max-age=300; includeSubDomains" always;
    
  3. 预加载列表:如果要提交到浏览器的 HSTS 预加载列表,必须包含 preload 指令,且 max-age 至少为 1 年(31536000 秒)

  4. 不可逆性:一旦客户端接收了 HSTS 头,在 max-age 过期前无法撤销

  5. 确保 HTTPS 完全可用:在启用 HSTS 前,确保所有子域名和资源都支持 HTTPS

  6. Nginx 版本:确保使用较新版本的 Nginx,旧版本可能需要额外配置才能正确发送 HSTS 头

完整示例

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # 启用HSTS (1年有效期,包含子域名)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # 其他安全头
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header X-XSS-Protection "1; mode=block";

    # SSL配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...';

    # 其他服务器配置...
}

# 将HTTP重定向到HTTPS
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

配置完成后,记得测试配置并重新加载 Nginx:

sudo nginx -t
sudo systemctl reload nginx