全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-20 8 分钟 ✍️ juanwangdev

NGINX SSL/TLS配置

HTTPS 是当前 Web 传输的标准协议,Nginx 原生支持 SSL/TLS 配置。

基础配置

启用 HTTPS

nginx
server {
    listen 443 ssl;
    server_name www.example.com;

    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;

    location / {
        root /var/www/html;
        index index.html;
    }
}
指令说明
listen 443 ssl监听 443 端口并启用 SSL
ssl_certificate服务器证书路径(包含中间证书)
ssl_certificate_key私钥路径

SSL 优化配置

nginx
server {
    listen 443 ssl;
    server_name www.example.com;

    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;

    # 协议版本
    ssl_protocols TLSv1.2 TLSv1.3;

    # 加密套件
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers on;

    # 会话缓存
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;

    # OCSP 装订
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/nginx/ssl/chain.crt;
    resolver 8.8.8.8;
}

SSL 协议版本

协议状态建议
SSLv3已废弃禁用
TLSv1.0已废弃禁用
TLSv1.1已废弃禁用
TLSv1.2推荐启用
TLSv1.3最新启用
nginx
# 仅启用 TLSv1.2 和 TLSv1.3
ssl_protocols TLSv1.2 TLSv1.3;

HTTP 自动跳转 HTTPS

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

server {
    listen 443 ssl;
    server_name www.example.com;
    # SSL 配置...
}

多域名 SSL 配置

SNI(单 IP 多证书)

nginx
server {
    listen 443 ssl;
    server_name site1.com;
    ssl_certificate /etc/nginx/ssl/site1.crt;
    ssl_certificate_key /etc/nginx/ssl/site1.key;
}

server {
    listen 443 ssl;
    server_name site2.com;
    ssl_certificate /etc/nginx/ssl/site2.crt;
    ssl_certificate_key /etc/nginx/ssl/site2.key;
}

注意事项

  • SNI 需要客户端支持,老旧浏览器(IE6/Android 2.x)不支持
  • ssl_certificate 文件应包含完整证书链(服务器证书 + 中间证书)

自签名证书测试

Bash
# 生成私钥
openssl genrsa -out server.key 2048

# 生成自签名证书
openssl req -new -x509 -days 365 -key server.key -out server.crt

注意事项

  • 自签名证书仅用于测试,生产环境需使用 CA 签发证书
  • Let's Encrypt 提供免费证书,可使用 certbot 自动续期

证书自动续期(Let's Encrypt)

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

# 获取证书
sudo certbot --nginx -d www.example.com -d example.com

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

HSTS 配置

强制浏览器使用 HTTPS 访问:

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

要点总结

  • HTTPS 配置核心指令:ssl_certificate、ssl_certificate_key、listen 443 ssl
  • 仅启用 TLSv1.2 和 TLSv1.3,禁用旧版本协议
  • ssl_session_cache 提升重复连接性能,shared 模式多进程共享
  • HTTP 跳转 HTTPS 使用 return 301 https://
  • SNI 支持单 IP 配置多个 SSL 证书
  • 生产环境使用 CA 签发证书,Let's Encrypt 提供免费方案
  • HSTS 头强制浏览器始终使用 HTTPS

📝 发现内容有误?点击此处直接编辑

← 上一篇 配置文件结构
下一篇 → Nginx安装与基本配置
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库