nginx SSL/HTTPS 配置

配置 HTTPS、SSL 证书和安全相关设置

语法

listen 443 ssl; ssl_certificate path; ssl_certificate_key path;

参数

参数说明示例级别
ssl_certificate 证书文件路径 ssl_certificate /etc/ssl/cert.pem; 常用
ssl_certificate_key 私钥文件路径 ssl_certificate_key /etc/ssl/key.pem; 常用
ssl_protocols 允许的 TLS 版本 ssl_protocols TLSv1.2 TLSv1.3; 常用
ssl_ciphers 加密套件 ssl_ciphers HIGH:!aNULL:!MD5; 进阶
ssl_session_cache SSL 会话缓存 ssl_session_cache shared:SSL:10m; 进阶

示例

基本 HTTPS 配置

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

    root /var/www/html;
}

Let's Encrypt 自动续期

# 安装 certbot
sudo apt install certbot python3-certbot-nginx
# 获取证书
sudo certbot --nginx -d example.com
# 自动续期(crontab)
0 0 1 * * certbot renew --quiet
certbot 会自动修改 Nginx 配置

HTTP/2 + HSTS

server {
    listen 443 ssl http2;
    server_name example.com;
    ssl_certificate ...;
    ssl_certificate_key ...;
    add_header Strict-Transport-Security "max-age=31536000" always;
}
启用 HTTP/2 和 HSTS 安全头

HTTP 强制跳转 HTTPS

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}
配合 HTTPS server 块使用

常见错误

SSL: error:0B080074:x509 certificate routines 证书文件格式错误或路径不对,确认使用 fullchain.pem(含中间证书)
ERR_SSL_PROTOCOL_ERROR 检查 ssl_protocols 配置,确保客户端支持的 TLS 版本在列表中

技巧

相关命令