hyperf 依赖 nginx 做 tls 终止:nginx 解密 https 后以 http 转发至 127.0.0.1:9501,并设置 x-forwarded-proto https 等头,hyperf 无需修改配置。

Hyperf 本身不直接处理 HTTPS,它依赖 Swoole 运行在 TCP 层,不内置 SSL 终止能力。要让 Hyperf 支持 HTTPS,必须通过 Nginx(或其他反向代理)做 TLS 终止:Nginx 接收加密的 HTTPS 请求,解密后以 HTTP 协议转发给 Hyperf 的监听端口(如 127.0.0.1:9501)。这是标准、安全且唯一推荐的方式。
确认 Nginx 已启用 SSL 模块
执行 nginx -V 2>&1 | grep -o with-http_ssl_module。若有输出,说明模块已编译;若无,需重新编译 Nginx 并加入 --with-http_ssl_module 参数。跳过此步会导致配置中出现 ssl_certificate 时报错“unknown directive”。
上传并设置证书权限
从 Let’s Encrypt(推荐 Certbot)、阿里云等平台下载 Nginx 类型证书包,解压后得到:
• 公钥证书文件(如 fullchain.pem 或 your_domain.crt)
• 私钥文件(如 privkey.pem 或 your_domain.key)
将二者上传至服务器安全路径,例如 /etc/letsencrypt/live/your_domain.com/ 或 /etc/nginx/ssl/。
运行以下命令确保私钥仅 root 可读写:
sudo chmod 600 /etc/nginx/ssl/your_domain.keysudo chown root:root /etc/nginx/ssl/*.key
配置 Nginx 反向代理 + HTTPS
在 /etc/nginx/conf.d/ 下新建配置文件(如 hyperf.conf),内容如下:
(注意替换 your_domain.com 和实际路径)
-
listen 443 ssl http2;— 必须带ssl关键字,否则不启用 TLS -
ssl_certificate指向证书链(含中间证书),如/etc/letsencrypt/live/your_domain.com/fullchain.pem -
ssl_certificate_key指向私钥,如/etc/letsencrypt/live/your_domain.com/privkey.pem -
proxy_pass http://127.0.0.1:9501;— Hyperf 默认 HTTP 监听端口,无需开启 HTTPS -
proxy_set_header X-Forwarded-Proto https;— 让 Hyperf 知道原始请求是 HTTPS,避免生成 HTTP 链接
同时建议添加 80 端口强制跳转:
server { listen 80; server_name your_domain.com; return 301 https://$host$request_uri; }
检查与启动
运行 sudo nginx -t 验证语法;若成功,执行 sudo systemctl reload nginx。
确保防火墙放行 443 端口(如 sudo ufw allow 443 或 firewall-cmd --permanent --add-port=443/tcp)。
Hyperf 服务保持原样运行(php bin/hyperf.php start),无需修改任何 PHP 配置或启动参数。











