ThinkPHP 8 在 Nginx 1.24 上伪静态关键在于三点:root 必须指向 public 目录,SCRIPT_FILENAME 必须用 $realpath_root 拼接,且必须用 try_files 规则(/index.php?$query_string)并禁用 if+rewrite;框架内还需开启 url_route_on、清空 url_html_suffix 并确保 ParseUrl 中间件存在。

ThinkPHP 8 在 Nginx 1.24 上配伪静态,关键不是版本高低,而是写法是否符合 TP8 的运行机制——它默认走 QUERY_STRING 模式(s= 参数已非必需),入口强制在 public/index.php,且依赖 $realpath_root 解析自动加载路径。Nginx 1.24 完全支持 try_files 和现代 fastcgi 参数,无需降级或补丁。
基础配置必须到位
确保以下三点全部满足,否则后续规则无效:
-
root 必须指向 public 目录,例如:
root /www/wwwroot/myapp/public;;若指向项目根目录,TP8 启动时会报Class 'think\App' not found且无提示 -
PHP 处理块中 SCRIPT_FILENAME 必须用 $realpath_root:
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;(不能用$document_root) -
PHP 进程已启动并监听正确端口,如
php-cgi.exe -b 127.0.0.1:9000 -c C:\php\php.ini,且info.php可正常访问
推荐使用 try_files(Nginx 1.24 原生支持)
在 server 块的 location / { } 中写入:
location / {<br> index index.php;<br> try_files $uri $uri/ /index.php?$query_string;<br>}
立即学习“PHP免费学习笔记(深入)”;
说明:
-
$uri匹配真实静态文件(如logo.png) -
$uri/匹配真实目录(如/admin/) -
/index.php?$query_string是兜底,完整透传所有 GET 参数,TP8 内部自动解析路由
禁用 if + rewrite(Nginx 1.24 下更易出问题)
旧式写法:if (!-e $request_filename) { rewrite ^(.*)$ /public/index.php?s=$1 last; }
在 Nginx 1.24 + Windows 或 PHP 8.2+ 环境下极易导致 PATH_INFO 为空、白屏或重定向循环。官方已明确标记为“不推荐”,TP8 文档也要求禁用。
若因历史原因必须保留,请确认:
- rewrite 路径写全:
/public/index.php?s=$1(不是/index.php) - 该
if块必须放在location ~ \.php$之前 -
last不可改为break,否则请求不会重新进入 PHP location 块
框架内必须同步启用路由
仅配 Nginx 不够,TP8 自身需确认 config/app.php 中:
-
'url_route_on' => true(路由开关打开) -
'url_html_suffix' => ''(空后缀,支持/user/list这类 URL) -
'pathinfo_depr' => '/'(与 URL 分隔符一致,虽 QUERY_STRING 模式下非强制,但保持统一更稳妥)
同时检查 app/middleware.php 是否保留了 think\middleware\ParseUrl::class,误删会导致路由不生效。



















