phpenv的nginx伪静态易失败,因其默认不支持path_info、缺失fastcgi_param path_info、不兼容try_files,且nginx版本旧,必须手动添加location /+if重写并补全fastcgi_split_path_info与path_info传递。

phpEnv 的 Nginx 配置下,ThinkPHP6 伪静态必须手动加 location / 块 + if (!-e $request_filename) 重写,且不能依赖 try_files —— 因为 phpEnv 默认不带 PATH_INFO 支持,也不自动注入 fastcgi_param PATH_INFO,直接套用宝塔或标准 Nginx 规则会 404 或无限重定向。
为什么 phpEnv 的 Nginx 伪静态容易失败
phpEnv 是 Windows 下轻量级 PHP 环境,其 Nginx 配置精简,默认不启用 PATH_INFO 解析,fastcgi_param PATH_INFO 这行几乎总是缺失或被注释;同时它不读 .htaccess,也不支持 try_files @rewrite 这类高级写法。你看到的「/index/index 报 404,但 /index.php/s=/index/index 能通」,就是典型症状。
常见错误现象:
- 访问
/index/test返回 Nginx 404(没进 TP6) - 访问
/index/test报错URL pathinfo not supported - 配置后出现
rewrite or internal redirection cycle(重定向循环)
在 phpEnv 的 nginx.conf 中添加 location 重写规则
打开 phpEnv 安装目录下的 nginx/conf/vhost/your-site.conf(或主配置中对应 server 块),在 location ~ \.php$ **之前** 插入以下内容:
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=$1 last;
}
}
关键点说明:
-
last不可换成break或redirect:只有last才触发重写后重新匹配 location,让请求落到location ~ \.php$块里 - 必须放在
location ~ \.php$之前:否则 PHP 文件优先匹配,if根本不执行 - phpEnv 的 Nginx 版本通常较老(如 1.18),
try_files行为不稳定,if是目前最可靠的选择
补全 fastcgi_param PATH_INFO 支持
仅重写不够。TP6 启动时需要 $_SERVER['PATH_INFO'],而 phpEnv 的默认 fastcgi_params 没传这玩意。找到你的 location ~ \.php$ 块,在 fastcgi_pass 后、include fastcgi.conf 前,**显式添加一行**:
fastcgi_param PATH_INFO $fastcgi_path_info;
同时确认该块中已有这行(没有就补上):
fastcgi_split_path_info ^(.+\.php)(/.+)$;
如果漏了 fastcgi_split_path_info,$fastcgi_path_info 就是空的,PATH_INFO 仍是 null。
验证与排错要点
改完配置后,必须:nginx -t 测试语法 → 手动重启 phpEnv 的 Nginx 服务(不是点「重载」,是彻底 stop 再 start)。
验证方式:
- 访问
https://localhost/index/test,应显示控制器输出(非 Nginx 404) - 访问一个不存在的路由如
/xyz,应返回 TP6 自带的 404 页面,而非 Nginx 默认页 - 查看
logs/error.log,重点搜rewrite or internal redirection cycle—— 出现说明if条件写错了,比如漏了空格或!写成! -e(中间有空格就失效)
最容易被忽略的是:phpEnv 的 Nginx 配置文件可能被多个 vhost 共用,改错文件或没改对 server 块会导致规则完全不生效;另外,Windows 下路径大小写不敏感,但 $request_filename 匹配的是真实磁盘路径,若 public 目录名写成 Public 而配置里写 root .../public,!-e 判断可能误判。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











