ThinkPHP 8.1 在 Docker 的 Nginx 容器中伪静态失效,核心原因是 PATH_INFO 未正确传递、root 未指向 public 父目录、或 Nginx 配置未通过 volume 挂载生效;必须设置 root 为 /var/www/html(public 上级)、location / 中用 try_files $uri $uri/ /public/index.php?$query_string、location ~ \.php$ 中显式配置 fastcgi_param PATH_INFO $fastcgi_path_info 和 fastcgi_split_path_info ^(.+\.php)(/.+)$,并确保 SCRIPT_FILENAME 为绝对路径且 php.ini 中 cgi.fix_pathinfo=1。

ThinkPHP 8.1 在 Docker 的 Nginx 容器里伪静态失效,核心不是“规则没写”,而是 PATH_INFO 没传过去、入口路径不对、或配置挂载没生效。直接套用 Apache 的 .htaccess 或简单加个 try_files 往往不行——Nginx 不解析 .htaccess,且 TP8.1 强制走 public/index.php,必须从 root、fastcgi_param、location 三处对齐。
root 必须指向 public 的父目录,不能是项目根
比如你的代码挂载在 /var/www/html,那里面结构是:
- /var/www/html/app/
- /var/www/html/public/ ← 入口目录(含 index.php)
- /var/www/html/runtime/
那么 Nginx 的 root 必须设为 /var/www/html,而不是 /var/www/html/public,否则 CSS/JS 404,且 try_files 找不到静态资源。
验证方式:访问 http://localhost/static/css/app.css 能正常加载,说明 root 设置正确。
立即学习“PHP免费学习笔记(深入)”;
location / 块里用 try_files,不依赖 PATH_INFO
TP8.1 默认启用 URL 参数模式(s 参数),推荐用更稳定、无需 PATH_INFO 的写法:
location / {
try_files $uri $uri/ /public/index.php?$query_string;
}注意三点:
- fallback 是 /public/index.php(带 public),不是 /index.php
- 末尾用 $query_string,不是 $args(避免特殊字符转义问题)
- 这条规则必须放在 所有 location ~ \.php$ 块之前,否则 PHP 路由请求会被提前匹配走
location ~ \.php$ 块必须透传 PATH_INFO(兼容路由调试)
虽然 try_files 方式可绕过 PATH_INFO,但 TP8.1 启动检测、部分扩展或自定义路由仍会读取 $_SERVER['PATH_INFO']。漏掉这行,可能触发 “URL pathinfo not supported” 错误:
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass php:9000; # 指向 PHP-FPM 容器
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
}关键点:
- SCRIPT_FILENAME 必须写死绝对路径,不要用 $document_root/public/index.php —— location 匹配偏差时容易出错
- fastcgi_split_path_info 正则末尾用 /.+(非空),不是 /* 或 /.*,否则可能截断错误
- 确保 PHP-FPM 容器中 php.ini 有 cgi.fix_pathinfo=1(默认开启,但某些 Alpine 镜像会关)
挂载配置要完整、可读、不覆盖全局
Docker 里改完配置重启就丢?别 exec 进去手改。正确做法:
- 把整个 server 块写进一个 default.conf 文件(含上面所有指令)
- 通过 volume 挂载到容器内:/path/to/default.conf → /etc/nginx/conf.d/default.conf
- 检查挂载后权限:ls -l /etc/nginx/conf.d/,确保 nginx 用户(如 www-data)有读权限
- 别挂载到 /etc/nginx/nginx.conf —— 容易破坏 events/http 等全局配置
启动后执行 nginx -t 验证语法,再 nginx -s reload 生效。



















