ThinkPHP5.1部署在二级目录(如/youdomain/)时,Nginx需用alias指向public目录、location精确匹配带尾斜杠路径、rewrite目标含/youdomain前缀,并配置app_sub_domain_deploy=>1以支持子目录URL生成。

ThinkPHP5.1 部署在二级目录(比如 /youdomain/)时,Nginx 的伪静态规则不能直接套用根目录写法,必须显式处理路径前缀,否则会出现 404 或入口文件被直接下载等问题。
关键点:location 要匹配二级目录路径,且 rewrite 中需保留前缀
假设你的项目完整访问路径是:https://example.com/youdomain/,入口文件为 youdomain/public/index.php,那么 Nginx 配置需满足:
-
location 块精准匹配
/youdomain/(末尾斜杠不能省,否则可能匹配到其他路径) -
rewrite 规则中,所有重写目标必须带上
/youdomain前缀,因为 PHP-FPM 接收的 SCRIPT_FILENAME 是基于网站根目录的绝对路径,而 URI 已被截断 - 确保
public/目录是 Web 可访问的根,即root应指向/path/to/youdomain/public,而不是项目根目录
Nginx 完整 location 配置示例
以下为适用于二级目录 /youdomain/ 的标准配置(请根据实际路径调整 root 和 fastcgi_param SCRIPT_FILENAME):
location /youdomain/ {
alias /var/www/html/youdomain/public/;
try_files $uri $uri/ /youdomain/index.php?$query_string;
<pre class="brush:php;toolbar:false;">location ~ \.php$ {
if (!-f $request_filename) { return 404; }
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_pass 127.0.0.1:9000; # 或 unix:/var/run/php/php8.1-fpm.sock
fastcgi_index index.php;
}
}
说明:
-
alias指向public/目录(注意不是root),这是二级目录下正确解析静态资源和入口的关键 -
try_files中使用/youdomain/index.php,而非/index.php,确保重写后 URI 路径仍落在该目录范围内 -
fastcgi_param SCRIPT_FILENAME $request_filename是核心:因为用了alias,$request_filename会自动拼出物理路径(如/var/www/html/youdomain/public/index.php),无需手动拼接 - 务必删除或注释掉可能存在的全局
location ~ \.php$ { ... }块,避免冲突
ThinkPHP 配置也要同步调整
仅 Nginx 改了还不够,TP5.1 需明确告知它运行在子目录:
- 在
public/index.php开头添加:define('APP_SUB_DOMAIN_DEPLOY', 1); - 或更推荐的方式:在
config/app.php中设置:'app_sub_domain_deploy' => 1, - 同时确认
url_domain_root为空(默认即可),系统会自动识别/youdomain/为 URL 根 - 生成 URL 时(如
url('index/index'))会自动带上前缀,无需手动拼
常见踩坑提醒
-
用 root 而非 alias:会导致
$request_filename错误,PHP 找不到入口文件 -
rewrite 写成
/index.php:请求会被转发到网站根目录下的 index.php,报错或跳转错乱 - 没加 trailing slash(/youdomain):Nginx 可能匹配失败,或把 /youdomainabc 也匹配进来
- public 目录权限不对或未开放执行:导致 403 或 PHP 文件被直接下载
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











