插件窝 干货文章 Nginx部署SSL证书的方法是什么

Nginx部署SSL证书的方法是什么

Nginx 证书 yourdomain SSL 820    来源:    2025-04-27

Nginx部署SSL证书方法指南

在Nginx上部署SSL证书可以实现HTTPS安全连接,以下是详细步骤:

准备工作

  1. 获取SSL证书文件(通常包括:

    • 证书文件(.crt或.pem)
    • 私钥文件(.key)
    • 可能还有CA证书链文件
  2. 确保Nginx已安装且支持SSL(检查nginx -V输出中是否有--with-http_ssl_module

部署步骤

1. 上传证书文件

将证书文件上传到服务器,推荐目录:

/etc/nginx/ssl/

包含: - yourdomain.crt (或.pem) - 主证书文件 - yourdomain.key - 私钥文件 - (可选) ca-bundle.crt - CA证书链文件

2. 配置Nginx

编辑Nginx配置文件(通常在/etc/nginx/sites-available/yourdomain.conf):

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

    # 证书路径
    ssl_certificate /etc/nginx/ssl/yourdomain.crt;
    ssl_certificate_key /etc/nginx/ssl/yourdomain.key;

    # (如果使用CA证书链)
    # ssl_trusted_certificate /etc/nginx/ssl/ca-bundle.crt;

    # 安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;

    # 其他配置...
    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;
}

3. 测试并重启Nginx

# 测试配置是否正确
sudo nginx -t

# 重启Nginx使配置生效
sudo systemctl restart nginx

高级配置选项

1. 启用HSTS

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

2. OCSP Stapling

ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;

3. 使用更安全的DH参数

sudo openssl dhparam -out /etc/nginx/dhparam.pem 2048

然后在配置中添加:

ssl_dhparam /etc/nginx/dhparam.pem;

验证SSL配置

  1. 使用浏览器访问https://yourdomain.com
  2. 使用在线工具检查:

  3. 命令行验证:

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

常见问题解决

  1. 证书链不完整:确保中间证书已包含在证书文件中
  2. 私钥不匹配:检查私钥是否与证书匹配 openssl x509 -noout -modulus -in cert.crt | openssl md5
  3. 权限问题:确保Nginx用户有读取证书文件的权限
  4. 防火墙阻止443端口:检查防火墙设置

通过以上步骤,您应该可以成功在Nginx上部署SSL证书并启用HTTPS安全连接。