Apache DocumentRoot 必须指向TP6的public/目录,不可将整个项目放入htdocs,否则暴露config/.env等敏感文件;应为TP6单独配置虚拟主机并启用AllowOverride All和mod_rewrite模块。

Apache DocumentRoot 必须指向 TP6 的 public/ 目录
不能把整个 TP6 项目(含 app/、config/、.env)直接扔进 htdocs,否则用户能通过浏览器直接访问 http://localhost/tp6/config/database.php —— 这是严重安全漏洞。TP6 的设计强制所有请求经由 public/index.php 入口统一调度,vendor/autoload.php 和配置加载路径都依赖 public/ 为 Web 根目录。
常见错误现象包括:
- 浏览器显示 “No input file specified.” 或空白页
-
http://localhost/tp6报 404,但http://localhost/tp6/public/index.php能显示 “Hello ThinkPHP6” - Apache 错误日志中出现
PHP Warning: require(): open_basedir restriction in effect
改 httpd.conf 还是配虚拟主机?推荐后者
直接修改全局 DocumentRoot 会破坏其他项目,且不便于多项目并行开发。更安全、清晰的做法是为 TP6 单独配一个虚拟主机,只影响该域名或路径。
以 Windows 为例(macOS / Linux 路径稍作替换):
立即学习“PHP免费学习笔记(深入)”;
- 编辑
D:\xampp\apache\conf\extra\httpd-vhosts.conf - 添加如下配置(注意路径用正斜杠或双反斜杠,避免转义问题):
<VirtualHost *:80>
DocumentRoot "D:/xampp/htdocs/tp6/public"
ServerName tp6.test
<Directory "D:/xampp/htdocs/tp6/public">
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
- 在系统
hosts文件(C:\Windows\System32\drivers\etc\hosts)末尾加一行:127.0.0.1 tp6.test - 重启 Apache,之后访问
http://tp6.test即可直达入口,无需拼/public/index.php
.htaccess 不生效?检查 AllowOverride All 和 mod_rewrite
TP6 的路由重写依赖 public/.htaccess,但它不会自动起作用。Apache 默认关闭 .htaccess 解析,且可能未启用重写模块。
必须确认以下两点:
-
<Directory>块中包含AllowOverride All(不是None或FileInfo) - Apache 已启用
mod_rewrite:在httpd.conf中取消注释这一行:LoadModule rewrite_module modules/mod_rewrite.so - 若仍 404,可在命令行运行
httpd -M | findstr rewrite(Windows)或apachectl -M | grep rewrite(macOS/Linux)验证模块是否已加载
Nginx 用户注意:root 路径结尾不能带斜杠
虽然你当前用的是 XAMPP(Apache),但很多开发者后期会迁移到 Nginx 生产环境。提前踩坑不如提前避坑:Nginx 配置中 root 指令必须写成绝对路径且**结尾无斜杠**。
错误写法(会导致 public/public/index.php 路径错乱):
root /var/www/tp6/public/;
正确写法:
root /var/www/tp6/public; try_files $uri $uri/ /index.php?$query_string;
漏掉 try_files 会导致除首页外所有路由返回 404;SCRIPT_FILENAME 必须设为 $document_root$fastcgi_script_name,不能硬编码路径。



















