← 返回首页

SSL/TLS证书配置与HTTPS安全加固

前言

HTTPS已成为网站标配。本文介绍SSL证书的申请、部署及安全配置方法。

一、证书申请

1.1 Let's Encrypt免费证书

# 安装certbot
apt install certbot python3-certbot-nginx

# 申请证书(自动配置Nginx)
certbot --nginx -d example.com -d www.example.com

# 自动续期(certbot自动配置cron)
certbot renew --dry-run

1.2 云厂商免费证书

阿里云、腾讯云等均提供免费DV证书,适合个人和小型项目使用。

二、Nginx HTTPS配置

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

    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;

    # TLS版本(禁用TLS 1.0/1.1)
    ssl_protocols TLSv1.2 TLSv1.3;

    # 加密套件
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;

    # 会话缓存
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;

    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

三、安全头配置

# HSTS - 强制HTTPS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN" always;

# 防止MIME类型嗅探
add_header X-Content-Type-Options "nosniff" always;

# XSS防护
add_header X-XSS-Protection "1; mode=block" always;

# CSP(内容安全策略)
add_header Content-Security-Policy "default-src 'self'" always;

四、HTTP到HTTPS跳转

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

五、SSL评分检测

推荐使用SSL Labs检测配置安全性:

  • 访问 https://www.ssllabs.com/ssltest/
  • 输入域名进行检测
  • 目标评分:A+ 级别
证书到期前30天应开始续期流程,建议配置自动续期避免证书过期导致服务中断。