ThinkPHP 8.0在Nginx下伪静态配置需三步:root必须指向public目录;主location用try_files $uri $uri/ /index.php?$query_string;PHP块中正确设置SCRIPT_FILENAME、PATH_INFO和PATH_TRANSLATED。

<p>Ubuntu 22.04 上用 Nginx 1.20 运行 ThinkPHP 8.0,关键是要正确处理 URL 重写(伪静态),让所有请求都经由 <strong>public/index.php</strong> 入口统一调度,同时避免暴露敏感路径、禁止直接访问 runtime 和 vendor 等目录。</p>
<H3>基础 server 块:支持 TP8 路由 + 静态资源直出</H3>
<p>以下是最简可用、生产环境推荐的完整 server 配置(假设网站根目录为 <strong>/var/www/myapp</strong>,且已将 ThinkPHP 的 <strong>public</strong> 目录设为 Nginx 根):</p>
<font color="#666">
<pre class="brush:php;toolbar:false;">
server {
listen 80;
server_name example.com;
root /var/www/myapp/public;
index index.php;
# 强制跳转 HTTPS(可选,如需启用请取消注释并配置证书)
# return 301 https://$server_name$request_uri;
# 处理静态资源:js/css/img 等直接返回,不走 PHP
location ~ \.(js|css|png|jpg|gif|svg|ico|woff2?|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# 拒绝访问敏感目录(runtime、vendor、config 等)
location ~ ^/(runtime|vendor|config|application|thinkphp|common|extend)/ {
deny all;
}
# 拒绝访问 .php 文件(除入口外),防恶意上传执行
location ~ \.php$ {
deny all;
}
# 主路由规则:所有非静态、非敏感路径,全部重写到 index.php
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP-FPM 处理入口(确保 php8.1-fpm 已安装并运行)
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
# ThinkPHP 8 需要 PATH_INFO 支持(重要!)
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
# 禁止访问 .htaccess、.env、.git 等隐藏文件
location ~ /\. {
deny all;
}
}
ThinkPHP 8 关键适配点说明
TP8 默认使用 PATH_INFO 模式解析路由(如 /user/list → index.php/user/list),Nginx 必须正确传递 PATH_INFO,否则路由 404。上面配置中:
修复 Core bailout 状态损坏安全问题,以及 BZ2、DOM、PDO、Opcache/JIT 内存与执行错误,改进 Unicode 字素处理、URL 解析、TLS 流状态、信号分发及会话错误处理。
-
try_files $uri $uri/ /index.php?$query_string确保请求落入 index.php - 第二个
location ~ \.php$块专用于执行 PHP,并显式设置fastcgi_param PATH_INFO $fastcgi_path_info -
fastcgi_path_info由 Nginx 自动提取(依赖于fastcgi_split_path_info,而snippets/fastcgi-php.conf已包含该指令)
验证与调试建议
配置完成后务必执行:
立即学习“PHP免费学习笔记(深入)”;
-
sudo nginx -t检查语法是否正确 -
sudo systemctl reload nginx重载配置 - 确认 PHP-FPM 正在运行:
systemctl status php8.1-fpm - 在
public/index.php顶部临时加var_dump($_SERVER['PATH_INFO'] ?? 'none');,访问http://example.com/user/test看是否输出/user/test - 检查日志:
tail -f /var/log/nginx/error.log和/var/log/php8.1-fpm.log
补充:如需兼容子目录部署(如 http://example.com/myapp/)
需额外调整:
- 在
server块内添加location /myapp/ { alias /var/www/myapp/public/; } - 修改
try_files行为,或改用rewrite ^/myapp/(.*)$ /$1 break;配合内部重写 - TP8 中需设置
'app_host' => 'http://example.com/myapp'并启用'url_html_suffix' => false等配合项


















