在 Debian 上为 LNMP 配置 SSL 的完整步骤
一 准备与前置检查
- 确保域名已正确解析到服务器,且防火墙放行 TCP 80/443。
- 安装组件(如尚未安装):
- Nginx:sudo apt update && sudo apt install nginx
- PHP-FPM(以 Debian 12 常见版本 PHP 8.2 为例):sudo apt install php-fpm php-mysql php-gd php-cli php-curl php-mbstring php-zip php-opcache php-xml php-mysqli
- 确认 PHP-FPM 监听方式与权限:
- 套接字方式:/etc/php/8.2/fpm/pool.d/www.conf 中一般为 listen = /run/php/php8.2-fpm.sock,且 listen.owner/listen.group 通常为 www-data;Nginx 进程用户需与其一致(常见为 www-data),否则会出现 502/13: Permission denied。可在 /etc/nginx/nginx.conf 将 user 设为 www-data,或将 PHP-FPM 改为 TCP 方式(listen = 127.0.0.1:9000)。
二 使用 Certbot 自动获取并配置 SSL(推荐)
- 安装 Certbot 及 Nginx 插件:sudo apt install certbot python3-certbot-nginx
- 获取并安装证书(同时自动配置 HTTP→HTTPS 重定向与 SSL 参数):sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
- 验证与续期:
- 语法检查:sudo nginx -t
- 重载:sudo systemctl reload nginx
- 测试自动续期:sudo certbot renew --dry-run
- 说明:Certbot 会自动修改站点配置,启用 443 ssl,并包含推荐的 SSL 参数与 DH 参数,证书路径通常为 /etc/letsencrypt/live/yourdomain.com/fullchain.pem 与 privkey.pem。
三 手动配置 SSL(适用于已有证书或自签 CA)
- 放置证书(示例):将 fullchain.pem 与 privkey.pem 放到 /etc/nginx/ssl/,权限建议 600。
- 站点配置示例(/etc/nginx/sites-available/yourdomain.com):
- 强制 HTTPS
- server { listen 80; server_name yourdomain.com www.yourdomain.com; return 301 https://$host$request_uri; }
- HTTPS 主机
- server { listen 443 ssl; server_name yourdomain.com www.yourdomain.com;
- ssl_certificate /etc/nginx/ssl/fullchain.pem;
- ssl_certificate_key /etc/nginx/ssl/privkey.pem;
- include /etc/letsencrypt/options-ssl-nginx.conf; # 若使用 Certbot 提供的通用配置
- ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # 若使用 Certbot 生成的 DH 参数
- 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/php8.2-fpm.sock; # 与 PHP-FPM 实际监听一致
- fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
- include fastcgi_params;
- }
- location ~ /.ht { deny all; }
- }
- 启用站点并生效:sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/ && sudo nginx -t && sudo systemctl reload nginx。
四 验证与常见问题
- 验证
- 访问 https://yourdomain.com,检查浏览器锁标识与证书信息。
- 使用 SSL 检测工具(如 SSL Labs)评估配置强度与链完整性。
- 查看证书到期:sudo certbot certificates;测试续期:sudo certbot renew --dry-run。
- 常见问题
- 502 Bad Gateway / Permission denied:核对 PHP-FPM 监听(socket 或 127.0.0.1:9000)与 Nginx 运行用户一致(常见为 www-data),并确保 socket 文件权限正确。
- 配置未生效:执行 nginx -t 检查语法,确认站点已软链到 sites-enabled 并已 reload/restart Nginx。
- 证书路径错误:手动配置时确保 ssl_certificate/ssl_certificate_key 指向正确的 fullchain.pem 与 privkey.pem。