插件窝 干货文章 Nginx怎么配置ssl证书实现https安全访问

Nginx怎么配置ssl证书实现https安全访问

Nginx SSL yourdomain 配置 203    来源:    2025-04-26

Nginx配置SSL证书实现HTTPS安全访问指南

准备工作

在开始配置之前,请确保: 1. 已购买域名并完成域名解析 2. 已获取SSL证书文件(通常包括.crt或.pem文件和.key文件) 3. 服务器已安装Nginx

详细配置步骤

1. 上传证书文件

将SSL证书文件上传到服务器,通常存放在/etc/nginx/ssl/目录下:

mkdir -p /etc/nginx/ssl
# 上传证书文件到该目录
# 通常会有两个文件:yourdomain.crt(或.pem)和yourdomain.key

2. 配置Nginx

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

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

    # SSL证书配置
    ssl_certificate /etc/nginx/ssl/yourdomain.crt;  # 证书文件路径
    ssl_certificate_key /etc/nginx/ssl/yourdomain.key;  # 私钥文件路径

    # 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;

    # 其他安全头
    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";

    # 网站根目录配置
    root /var/www/yourdomain;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
}

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

3. 检查配置并重启Nginx

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

# 如果测试通过,重启Nginx使配置生效
systemctl restart nginx

高级配置选项

1. 启用OCSP Stapling

在SSL配置部分添加:

ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/ssl/yourdomain-chain.crt;  # 中间证书链文件
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;

2. 配置HTTP/2

在443端口的监听行添加http2

listen 443 ssl http2;

3. 使用更安全的加密套件

ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';

验证配置

  1. 使用浏览器访问https://yourdomain.com,检查是否有安全锁标志
  2. 使用SSL Labs测试工具:https://www.ssllabs.com/ssltest/
  3. 使用命令行验证:
curl -I https://yourdomain.com

常见问题解决

  1. 证书链不完整:确保中间证书已正确包含在证书文件中
  2. 私钥不匹配:确认.key文件与证书匹配
  3. 权限问题:确保Nginx用户有读取证书文件的权限 bash chmod 600 /etc/nginx/ssl/* chown root:root /etc/nginx/ssl/*
  4. 端口未开放:确保防火墙已开放443端口

证书自动续期

如果使用Let's Encrypt证书,可以设置自动续期:

# 使用certbot-auto工具
certbot renew --dry-run
# 设置定时任务
crontab -e
# 添加以下内容(每月1号凌晨3点检查续期)
0 3 1 * * /usr/bin/certbot renew --quiet

通过以上步骤,您的网站应该已经成功配置了HTTPS安全访问。