nginx配置ssl证书需三步:获取证书(推荐certbot申请let’s encrypt免费证书)、修改nginx配置启用https(监听443端口、指定证书路径、设http跳转)、验证并重启服务;同时须确保proxy_pass指向hyperf实际监听地址(如127.0.0.1:9501),并配置自动续期。

Hyperf 本身不直接处理 HTTPS,必须靠 Nginx(或类似反向代理)来终结 SSL。所以部署免费 SSL 证书的核心动作不在 Hyperf 代码里,而是在 Nginx 配置 + 证书申请 + 反向代理打通三步上。
申请免费 SSL 证书(推荐 Certbot)
用 Let’s Encrypt 的 Certbot 是最主流、自动化程度最高的方式:
- 登录服务器(Linux),确保已安装 nginx 且网站可通过 HTTP 正常访问(比如
http://pay.yourdomain.com能返回 Hyperf 的欢迎页或接口) - 执行:
sudo apt install certbot python3-certbot-nginx(Ubuntu/Debian)或sudo yum install certbot python2-certbot-nginx(CentOS 7) - 运行:
sudo certbot --nginx -d pay.yourdomain.com(替换为你的真实二级域名) - Certbot 会自动检测 Nginx 配置、申请证书、修改 conf 文件,并启用 HTTPS 重定向
- 证书默认存于:
/etc/letsencrypt/live/pay.yourdomain.com/,含fullchain.pem和privkey.pem
Nginx 配置要匹配 Hyperf 监听地址
这是 502 错误高发区,务必核对清楚:
- Hyperf 默认监听
127.0.0.1:9501(不是0.0.0.0),所以 Nginx 的proxy_pass必须指向该地址 - 确认
config/autoload/server.php中:'host' => '127.0.0.1','port' => 9501(整数,非字符串) - Nginx server 块需同时监听 80 和 443,并做 HTTP → HTTPS 跳转:
示例片段(精简):
server {
listen 80;
server_name pay.yourdomain.com;
return 301 https://$server_name$request_uri;
}
<p>server {
listen 443 ssl http2;
server_name pay.yourdomain.com;</p><pre class="brush:php;toolbar:false;">ssl_certificate /etc/letsencrypt/live/pay.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/pay.yourdomain.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:9501;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}}
验证与续期
证书 90 天过期,必须设自动续期:
- 测试手动续期:
sudo certbot renew --dry-run - 添加定时任务(推荐每月 1 号凌晨 3 点):
0 3 1 * * root certbot renew --quiet --no-self-upgrade - 验证是否生效:访问
https://pay.yourdomain.com,浏览器地址栏显示锁图标;用curl -I https://pay.yourdomain.com应返回200 OK - 若仍报 502,请立即检查:
netstat -tuln | grep :9501(看 Hyperf 是否真在监听)、systemctl status nginx(Nginx 是否运行)、tail -f /var/log/nginx/error.log(具体错误线索)
特别注意 Docker 环境下的 proxy_pass
如果 Hyperf 运行在 Docker 容器中,Nginx 在宿主机,proxy_pass http://127.0.0.1:9501 会连到宿主机而非容器 —— 这是常见坑:
- 方案一(推荐):Nginx 也放进 Docker,用自定义 bridge 网络,
proxy_pass http://hyperf:9501(服务名即容器名) - 方案二(开发快速):Docker 启动时加
--network host,让 Hyperf 直接使用宿主机网络,保持127.0.0.1:9501可达 - 方案三(Mac/Win):用
host.docker.internal替代127.0.0.1;Linux 需额外加--add-host=host.docker.internal:host-gateway











