温馨提示×

Debian LNMP如何加SSL

小樊
51
2026-07-02 04:35:15
栏目: 云计算

Debian 上给 LNMP(Linux + Nginx + MySQL/MariaDB + PHP) 增加 SSL(HTTPS),最常用、最推荐的做法是:
使用 Let’s Encrypt 免费证书(Certbot)

下面给你一套 完整实操流程,从准备到生效。


一、准备条件(必须满足)

  1. Debian 系统
  2. 已安装 Nginx
  3. 域名已解析到服务器公网 IP
  4. 80 / 443 端口已放行

例如:

example.com
www.example.com

二、安装 Certbot(Let’s Encrypt)

1️⃣ 更新系统

sudo apt update
sudo apt upgrade -y

2️⃣ 安装 Certbot 和 Nginx 插件

sudo apt install certbot python3-certbot-nginx -y

三、确认 Nginx 配置(关键)

示例 Nginx 站点配置

server {
    listen 80;
    server_name example.com www.example.com;

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

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php-fpm.sock;
    }
}

server_name 必须和你的域名一致
✅ 访问 http://example.com 要能正常打开


四、申请并自动配置 SSL(最简单)

一条命令搞定

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

执行过程中会:

  • 自动申请证书
  • 自动修改 Nginx 配置
  • 自动启用 HTTPS
  • 自动配置 301 跳转

推荐新手直接用这个


五、手动申请证书(可选)

如果你不想自动改 Nginx:

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

然后再手动改 Nginx。


六、手动 Nginx SSL 配置(了解用)

Certbot 通常自动生成类似配置:

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

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

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

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php-fpm.sock;
    }
}

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

七、测试证书是否生效

浏览器访问:

https://example.com

或用命令测试:

curl -I https://example.com

八、证书自动续期(Let’s Encrypt 有效期 90 天)

测试续期

sudo certbot renew --dry-run

自动续期

Debian 默认已有 systemd 定时任务:

systemctl status certbot.timer

无需手动操作


九、常见问题排查

❌ 申请失败

Failed to obtain certificate

✅ 检查:

  • 80 端口是否被防火墙拦截
  • 域名解析是否正确
  • Nginx 是否运行

❌ HTTPS 访问 502

✅ 通常是 PHP-FPM 没启动:

sudo systemctl restart php-fpm
sudo systemctl restart nginx

十、总结(最简流程)

apt update
apt install certbot python3-certbot-nginx
certbot --nginx -d yourdomain.com

几分钟即可 HTTPS


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

  • Debian 版本(10 / 11 / 12)
  • 单域名 / 多域名 / 泛域名
  • 是否用 LNMP一键包

我可以给你 更精准的配置方案

0