插件窝 干货文章 Nginx与SSL:配置HTTPS保护Web服务器

Nginx与SSL:配置HTTPS保护Web服务器

yourdomain 证书 配置 SSL 64    来源:    2025-04-20

Nginx与SSL:配置HTTPS保护Web服务器

HTTPS已成为现代Web服务器的标准配置,它能加密客户端与服务器之间的通信,保护数据安全。以下是使用Nginx配置HTTPS的详细指南。

1. 获取SSL证书

免费证书选项

  • Let's Encrypt:最流行的免费证书颁发机构
  • Cloudflare:提供免费SSL证书和CDN服务
  • ZeroSSL:提供免费90天证书

付费证书选项

  • DigiCert
  • GlobalSign
  • Comodo

2. 使用Let's Encrypt获取证书

# 安装Certbot工具
sudo apt install certbot python3-certbot-nginx  # Ubuntu/Debian
sudo yum install certbot python3-certbot-nginx  # CentOS/RHEL

# 获取证书并自动配置Nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

# 仅获取证书(不自动配置)
sudo certbot certonly --nginx -d yourdomain.com -d www.yourdomain.com

3. 手动配置Nginx SSL

基本HTTPS配置

server {
    listen 443 ssl;
    server_name yourdomain.com www.yourdomain.com;

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

    # SSL配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
    ssl_ecdh_curve secp384r1;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;
    ssl_stapling on;
    ssl_stapling_verify on;

    # 其他配置...
    location / {
        root /var/www/html;
        index index.html;
    }
}

HTTP重定向到HTTPS

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

4. 高级SSL配置

启用HTTP/2

server {
    listen 443 ssl http2;
    # 其他配置...
}

OCSP Stapling配置

ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/letsencrypt/live/yourdomain.com/chain.pem;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;

安全头部

add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";

5. 测试SSL配置

使用OpenSSL测试

openssl s_client -connect yourdomain.com:443 -servername yourdomain.com

在线测试工具

6. 证书自动续期

Let's Encrypt证书有效期为90天,设置自动续期:

# 测试续期
sudo certbot renew --dry-run

# 设置cron任务自动续期
sudo crontab -e
# 添加以下内容(每天检查续期)
0 12 * * * /usr/bin/certbot renew --quiet

7. 常见问题解决

证书不信任

  • 确保证书链完整(使用fullchain.pem)
  • 检查中间证书是否包含

混合内容警告

  • 确保所有资源(CSS, JS, 图片)都通过HTTPS加载
  • 使用内容安全策略(CSP)头

性能问题

  • 启用会话恢复(session resumption)
  • 考虑使用TLS 1.3减少握手时间
  • 启用OCSP Stapling减少验证时间

通过以上配置,您的Nginx服务器将提供安全的HTTPS连接,保护用户数据并提升网站可信度。