ThinkPHP上线需正确配置Nginx:root必须指向public目录,启用try_files路由重写,禁止敏感路径访问,屏蔽隐藏文件,上传目录禁PHP执行,关闭PHP错误显示,配置静态资源缓存与Gzip压缩,并验证首页、路由及响应头。

ThinkPHP项目上线不是把代码丢上去就完事,关键在Nginx能否准确把请求交到public/index.php,同时守住安全底线、压住性能瓶颈。配置错一条规则,轻则404、路由失效,重则敏感文件泄露、PHP错误满屏。
入口路径必须指向 public 目录
ThinkPHP 6+ 强制要求 Web 根目录为 public/,不能是项目根目录。否则 .env、config/、app/ 等目录可能被直接访问。
-
正确做法:Nginx 的
root指令必须明确指向/var/www/myapp/public(路径按实际调整) -
错误写法:
root /var/www/myapp;+location / { try_files $uri $uri/ /public/index.php?$query_string; }—— 这样会导致/public/路径暴露,且静态资源 404 风险高 - 验证方式:访问
http://yourdomain.com/robots.txt或任意不存在的图片,看是否返回 404 而非 PHP 错误;再访问http://yourdomain.com/.env,应返回 403 或 404
URL重写要兼顾 PATH_INFO 和兼容性
ThinkPHP 默认使用 PATH_INFO 模式解析路由(如 /index/user/list),Nginx 原生不拆分 PATH_INFO,需显式支持或改用查询参数模式。
- 推荐配置(无 if、无 rewrite、更健壮):
location / { try_files $uri $uri/ /index.php?$query_string; } - 若必须支持原生 PATH_INFO(如老项目依赖
$_SERVER['PATH_INFO']),用fastcgi_split_path_info:location ~ \.php(/|$) { fastcgi_split_path_info ^(.+\.php)(/.*)$; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; fastcgi_pass unix:/run/php/php8.1-fpm.sock; } - 避免写
if (!-e $request_filename)—— Nginx 官方明确不推荐在 location 外使用 if,易引发重写循环或逻辑异常
安全加固不可跳过的关键项
线上环境默认就是攻击面,几行配置就能堵住大部分低危漏洞。
立即学习“PHP免费学习笔记(深入)”;
- 禁止访问敏感路径:
location ~ ^/(app|config|database|extend|runtime|vendor|tests)/ { deny all; } - 屏蔽隐藏文件与配置文件:
location ~ /\.(env|git|htaccess|svn|log|bak|swp|yml|yaml|xml|md)$ { deny all; } - 上传目录禁执行(如
public/uploads/):location ^~ /uploads/ { location ~ \.php$ { deny all; } } - PHP 层面同步关闭错误显示:
display_errors = Off(php.ini)+ ThinkPHP 配置'show_error_msg' => false
性能优化从基础配置开始
不用上 Redis 或 CDN,仅靠 Nginx 几项设置就能明显提速。
- 静态资源强缓存(JS/CSS/图片等):
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ { expires 1y; add_header Cache-Control "public, immutable"; access_log off; } - 启用 Gzip 压缩(文本类资源):
gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; gzip_min_length 1k;
- FastCGI 缓存(适合内容更新不频繁的后台或门户页):
fastcgi_cache_path /var/cache/nginx/thinkphp levels=1:2 keys_zone=thinkphp:100m inactive=60m; fastcgi_cache_key "$scheme$request_method$host$request_uri"; location ~ \.php$ { fastcgi_cache thinkphp; fastcgi_cache_valid 200 302 10m; fastcgi_cache_use_stale error timeout updating http_500; }
部署后务必执行三步验证:访问首页看是否正常加载、点击任意二级路由确认不跳转到 index.php、用 curl -I 检查静态资源返回 200 + 正确的 Cache-Control 和 Content-Encoding: gzip 头。不复杂但容易忽略。



















