温馨提示×

Debian怎么配置Nginx SSL

小樊
34
2026-08-18 05:29:38
栏目: 云计算

下面是在 Debian 系统上配置 Nginx SSL(HTTPS) 的完整流程,适用于 Debian 10/11/12,包含自签名证书Let’s Encrypt 免费证书两种方式。


一、准备工作

1. 更新系统

sudo apt update
sudo apt upgrade -y

2. 安装 Nginx

sudo apt install nginx -y

3. 确认 Nginx 已启动

sudo systemctl status nginx

二、方式一:使用自签名 SSL(测试用)

1. 创建证书存放目录

sudo mkdir -p /etc/nginx/ssl

2. 生成私钥和自签名证书

sudo openssl req -x509 -nodes -days 365 \
  -newkey rsa:2048 \
  -keyout /etc/nginx/ssl/nginx.key \
  -out /etc/nginx/ssl/nginx.crt

按提示填写:

  • Common Name:域名或 IP(如 example.com192.168.1.10

3. 配置 Nginx SSL

编辑站点配置:

sudo nano /etc/nginx/sites-available/default

示例配置:

server {
    listen 443 ssl;
    server_name example.com;

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

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    root /var/www/html;
    index index.html;

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

# HTTP 自动跳转 HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

4. 测试并重载 Nginx

sudo nginx -t
sudo systemctl reload nginx

三、方式二:使用 Let’s Encrypt(生产环境 ✅)

1. 安装 Certbot

sudo apt install certbot python3-certbot-nginx -y

2. 申请 SSL 证书

sudo certbot --nginx -d example.com -d www.example.com

流程说明:

  • 输入邮箱
  • 同意服务条款
  • 选择是否重定向 HTTP → HTTPS(推荐选 2

3. 自动续期测试

sudo certbot renew --dry-run

✅ Certbot 已自带 systemd timer,无需手动设置。


四、验证 SSL 是否成功

浏览器访问:

https://example.com

或使用:

curl -I https://example.com

五、常见问题

1. 443 端口不通

检查防火墙:

sudo ufw allow 'Nginx Full'

2. 证书路径错误

确保:

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

3. 多个站点 SSL

为每个域名单独配置 server {},并使用对应证书。


六、推荐安全配置(可选)

ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-AES256-GCM-SHA384';
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;

如果你愿意,可以告诉我:

  • ✅ Debian 版本
  • ✅ 是否已有域名
  • ✅ 是否用于生产环境

我可以帮你生成完整可用的 Nginx 配置文件

0