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

nginx怎么配置ssl证书实现https访问

证书 yourdomain SSL 配置 200    来源:    2025-04-26

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

要在Nginx上配置SSL证书实现HTTPS访问,您需要完成以下步骤:

1. 获取SSL证书

首先,您需要获取有效的SSL证书,可以选择:

  • 商业证书:从DigiCert、GlobalSign等CA购买
  • 免费证书:使用Let's Encrypt(推荐)
  • 自签名证书:仅用于测试环境

使用Let's Encrypt获取免费证书(推荐)

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

# 获取证书(替换yourdomain.com)
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

2. Nginx SSL配置

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

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

    # SSL证书路径
    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 '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';
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling on;
    ssl_stapling_verify on;

    # 其他配置...
    root /var/www/yourdomain.com/html;
    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配置
sudo nginx -t

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

4. 设置证书自动续期(Let's Encrypt证书)

Let's Encrypt证书每90天过期,设置自动续期:

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

# 添加crontab任务自动续期
sudo crontab -e

添加以下行(每天检查并续期):

0 12 * * * /usr/bin/certbot renew --quiet

5. 验证HTTPS配置

访问您的网站,确认: 1. 浏览器地址栏显示安全锁标志 2. 使用SSL Labs测试工具检查配置安全性

高级配置选项

启用HTTP/2(性能提升)

listen 443 ssl http2;

OCSP Stapling优化

ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/letsencrypt/live/yourdomain.com/chain.pem;

安全头设置

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

常见问题解决

  1. 证书不信任:确保证书链完整,中间证书已包含
  2. 混合内容警告:确保所有资源(图片、JS、CSS)都通过HTTPS加载
  3. SSL协议错误:检查ssl_protocols配置,禁用不安全的TLS 1.0/1.1

如需进一步帮助,请提供具体的错误信息或配置细节。