ThinkPHP在Nginx下需分层设防:root必须指向public目录(如/www/wwwroot/myapp/public;),主location用try_files $uri $uri/ /index.php?$query_string;,顶部拦截.git、.env等敏感路径并禁用autoindex,静态资源单独配置root+try_files,杜绝目录泄露与路由失效。

要让 ThinkPHP 在 Nginx 下既支持伪静态访问,又防止目录泄露(比如直接列出 /public/、/runtime/ 或访问 .env、.git 等敏感文件),不能只配一条重写规则,必须分层设防:既正确转发请求给 index.php,又严格限制静态资源和危险路径的可访问范围。
一、root 必须指向 public 目录,且末尾不加斜杠
这是防泄露的第一道防线。ThinkPHP 6/8 入口已移入 public/,若 root 错配到项目根目录(如 /www/wwwroot/myapp),不仅路由失效,更会暴露 app/、config/、vendor/ 等完整结构。
- ✅ 正确写法:
root /www/wwwroot/myapp/public;(注意末尾分号,无多余斜杠) - ❌ 错误写法:
root /www/wwwroot/myapp;或root /www/wwwroot/myapp/public/; - 配置后务必执行
nginx -t && nginx -s reload生效
二、静态资源 location 要用 root + try_files,禁用 autoindex
对图片、JS、CSS 等静态资源单独配置 location,避免它们被主规则误交由 PHP 处理,同时杜绝目录遍历和自动索引。
- 在
server块中添加(示例针对/static/): location /static/ {-
alias /www/wwwroot/myapp/public/static/;← 不推荐 alias -
root /www/wwwroot/myapp/public;← 推荐 root -
try_files $uri =404; -
autoindex off; -
expires 30d; }- 关键点:root 后路径不含
/static/,$uri 自动拼接;try_files $uri =404确保只响应真实存在的文件
三、顶部拦截敏感路径与遍历特征
在 server 块最上方(早于所有其他 location)加入黑名单和路径校验,从源头阻断常见攻击尝试。
立即学习“PHP免费学习笔记(深入)”;
- 屏蔽典型敏感前缀:
location ~ ^/(?:\.(?:git|env|htaccess)|config|runtime|database|backup|logs) {-
return 403; }- 拦截含
../的 URI(防目录穿越): if ($uri ~ "\.\.") {-
return 403; }- 注意:该
if必须放在location ~ \.php$之前,否则可能被跳过
四、主 location 使用 try_files,不依赖 if 判断
避免旧式 if (!-e $request_filename) 引发的 PATH_INFO 丢失、POST 数据截断等问题(尤其在 Windows 或 PHP 8+ 下易白屏)。
- 主路由规则应为:
location / {-
try_files $uri $uri/ /index.php?$query_string; }- 确保 PHP 处理块含关键参数:
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; - 若部署在子目录(如
/myapp/),则 fallback 改为:/myapp/index.php?$query_string;



















