ThinkPHP在Nginx下实现伪静态的关键是正确传递PATH_INFO以解析路由,必须在location ~ .php$块中配置fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name、PATH_INFO $fastcgi_path_info和SCRIPT_NAME /index.php,并配合fastcgi_split_path_info指令提取路径信息。

ThinkPHP 在 Nginx 下实现伪静态,关键在于正确传递 PATH_INFO,让框架能解析出路由(如 /index/index/hello),而不是被当作静态路径 404。核心是配置好 fastcgi_param,尤其要处理好 SCRIPT_FILENAME 和 PATH_INFO 的值。
必须设置的 fastcgi_param 项
在 location ~ \.php$ 块中,至少需包含以下三项(顺序无关,但缺一不可):
-
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;用$realpath_root替代$document_root,避免符号链接导致路径错误;确保 PHP 真实加载到入口文件(如public/index.php) -
fastcgi_param PATH_INFO $fastcgi_path_info;这是 ThinkPHP 解析 URL 路由的关键。Nginx 需提前通过fastcgi_split_path_info提取PATH_INFO,否则该变量为空 -
fastcgi_param SCRIPT_NAME /index.php;显式固定为入口文件名(不带路径),防止某些部署下SCRIPT_NAME被设为子目录路径,干扰路由识别
完整 location 块示例(ThinkPHP 6/8 推荐)
假设项目根目录为 /var/www/myapp,入口在 public/ 下:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ ^/index\.php(/|$) {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param HTTPS $https if_not_empty;
fastcgi_param HTTP_PROXY "";
fastcgi_param HTTP_HOST $http_host;
fastcgi_param HTTP_X_REAL_IP $remote_addr;
fastcgi_param HTTP_X_FORWARDED_FOR $proxy_add_x_forwarded_for;
fastcgi_param HTTP_X_FORWARDED_PROTO $scheme;
include fastcgi_params;
}
注意:fastcgi_split_path_info 必须放在 fastcgi_param 之前,否则 $fastcgi_path_info 不会生效。
常见错误与排查点
-
直接用
$document_root$fastcgi_script_name:当项目用软链部署时,PHP 可能读取到链接目标路径,导致__DIR__错乱,建议统一用$realpath_root -
漏写
fastcgi_split_path_info:PATH_INFO 恒为空,ThinkPHP 收不到路由信息,所有请求都进首页或报错 -
SCRIPT_NAME 写成
$fastcgi_script_name:比如访问/admin/index.php/user/list时,SCRIPT_NAME 变成/admin/index.php,ThinkPHP 误判应用入口 -
没启用
pathinfo支持:确认 ThinkPHP 配置'url_pathinfo_depr' => '/'且'url_model' => 2(PATHINFO 模式)
验证是否生效的小技巧
临时在 public/index.php 开头加一行:
file_put_contents('/tmp/php_env.log', print_r($_SERVER, true), FILE_APPEND);
访问一个带参数的 URL(如 /index/index/hello),查看日志里是否有:
-
SCRIPT_FILENAME指向正确的public/index.php -
PATH_INFO值为/index/index/hello -
SCRIPT_NAME值为/index.php
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











