Nginx + Let’s Encrypt 免费 SSL 证书部署全流程实战教程(CentOS)


1. 环境准备

  • 操作系统:CentOS 7/8 或类似
  • 已安装 Nginx,并确保网站能正常通过 HTTP(80端口)访问
  • 域名已解析指向服务器公网 IP,且 DNS 生效
  • 服务器有 root 权限或 sudo 权限

2. 安装 Certbot(Let’s Encrypt 客户端)

Certbot 是 Let’s Encrypt 官方推荐的自动申请、安装、续期证书的工具。

2.1 安装 EPEL 仓库(CentOS 7示例)

sudo yum install epel-release -y

2.2 安装 Certbot 和 Nginx 插件

sudo yum install certbot python3-certbot-nginx -y

3. 申请 SSL 证书

3.1 检查 nginx 配置,确保网站可以通过 HTTP 访问

确认你的 Nginx 站点配置有:

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

root /www/wwwroot/yourdomain;
index index.php index.html;

location / {
try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
# PHP fastcgi 配置,根据实际修改
include fastcgi_params;
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}

重载 nginx:

sudo nginx -t
sudo systemctl reload nginx

3.2 运行 Certbot 自动申请证书

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

过程会提示输入邮箱,是否同意协议,是否自动重定向 HTTP 到 HTTPS。

推荐选择自动重定向,这样 certbot 会帮你改写 nginx 配置,实现 80 跳 443。


4. 验证 HTTPS 站点

申请成功后,Certbot 会自动更新你的 nginx 配置,监听 443 端口,配置好证书路径。

你可以通过浏览器访问:

https://yourdomain.com

确认页面正常且浏览器显示安全锁。


5. 自动续期设置

Certbot 默认安装时,会添加系统定时任务(cron 或 systemd timer)自动续期证书。

可以用以下命令测试续期过程:

sudo certbot renew --dry-run

成功时会看到模拟续期成功提示。


6. 手动配置 HTTPS(可选)

如果你想手动配置 nginx 证书,也可以:

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

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

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

root /www/wwwroot/yourdomain;
index index.php index.html;

location / {
try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/tmp/php-cgi.sock; # PHP-FPM socket,根据实际修改
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}

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

# 强制跳转到 HTTPS
return 301 https://$host$request_uri;
}

7. 常见问题排查

  • 证书申请失败:确认域名解析正确,端口 80/443 没被防火墙或安全组阻断
  • Nginx 配置错误:使用 nginx -t 验证语法,查看错误日志 /var/log/nginx/error.log
  • 证书续期失败:确认自动任务正常执行,手动测试续期 certbot renew --dry-run
  • PHP 版本兼容:确保 nginx 配置的 fastcgi_pass 指向正确版本的 PHP-FPM socket

8. 总结

  • 使用 Certbot 是最简单方便申请 Let’s Encrypt 证书方式
  • 申请时选择自动重定向,可以自动完成 HTTP→HTTPS 跳转配置
  • 配置时注意 PHP-FPM 版本与路径,避免版本不匹配问题导致代码执行异常
  • 及时测试续期,确保证书不会过期导致网站不安全

已发布

分类

来自

标签:

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注