thinkphp 5 在 apache 上正常运行的前提是:documentroot 必须指向 public 目录,启用 mod_rewrite 模块,并在对应 directory 块中设置 allowoverride all 和 require all granted,同时显式禁止 runtime、app、config 等敏感目录的 http 访问,否则将导致 404、白屏或源码泄露。

ThinkPHP 5 能在 Apache 上跑起来,前提是 DocumentRoot 必须指向 public 目录,且 mod_rewrite 启用、.htaccess 生效——缺一不可。否则你看到的不是白屏就是 404,甚至 runtime 目录被直接下载。
DocumentRoot 必须设为 public 目录
ThinkPHP 5 的入口隔离机制强制要求 Web 可访问路径仅限 public/,其余如 app/、runtime/、config/ 都不能暴露在 HTTP 下。如果 DocumentRoot 指向项目根目录(比如 /var/www/myapp),攻击者访问 https://example.com/runtime/log/202605.log 就可能直接下载日志文件。
-
DocumentRoot正确值应为/var/www/myapp/public(Linux)或C:/xampp/htdocs/myapp/public(Windows) - 不能靠
Alias或Redirect补救;必须在<virtualhost></virtualhost>块内显式设置 - 若用 phpstudy 等集成环境,需在「网站目录」中选中
public子目录,而非整个项目文件夹 - Windows 下路径含中文或空格会导致 Apache 启动失败,务必避免
mod_rewrite 必须启用且 AllowOverride All
ThinkPHP 5 的路由依赖 Apache 的重写能力。public/.htaccess 文件只有在对应 <directory></directory> 块允许覆盖时才生效。很多最小化安装或 Docker 镜像默认是 AllowOverride None,这时所有带参数的 URL(如 /index/user/profile)都会 404。
- 确认模块已加载:
a2enmod rewrite(Debian/Ubuntu)或检查httpd -M | grep rewrite(RHEL/CentOS) - 在
<directory></directory>块中必须包含:AllowOverride All和Require all granted -
.htaccess文件权限需为644,且 Apache 进程用户(如www-data)有读取权 - 别信“默认开启”——Apache 2.4+ 默认就是
AllowOverride None
敏感目录必须显式禁止 HTTP 访问
即使 DocumentRoot 正确指向 public,攻击者仍可能通过构造路径尝试越权访问。例如,若服务器支持符号链接或存在配置疏漏,../runtime/ 仍可能被解析出来。
- 在 Apache 主配置或虚拟主机中添加如下规则(放在
<directory></directory>外):<directory> Require all denied </directory><directory> Require all denied </directory><directory> Require all denied </directory> - 也可在
public/.htaccess中追加:RedirectMatch 403 ^/(runtime|app|config)/ - 检查是否真生效:手动请求
http://yourdomain.com/../runtime/,应返回 403 而非 404 或内容
常见错误现象与快速验证点
部署后打不开、跳转错乱、首页空白,往往不是代码问题,而是这几处卡住了。
- 访问
http://localhost/info.php显示 PHP 信息 → 说明 PHP 和 Apache 基础通了 - 访问
http://localhost/public/显示 ThinkPHP 欢迎页 → 说明DocumentRoot和基础权限没问题 - 访问
http://localhost/public/index.php/hello成功 → 说明 PHP 路由能走通,但重写未生效 - 访问
http://localhost/public/hello404 →mod_rewrite或AllowOverride未配好 - 访问
http://localhost/runtime/log/返回日志列表或下载 → 敏感目录未屏蔽,严重风险
最易被忽略的是 AllowOverride All 的作用范围——它只对当前 <directory></directory> 生效,且不会继承到子目录。如果你把项目放在多层嵌套路径下,必须确保该路径的每一级父目录都显式配置了权限控制,否则重写规则就只是摆设。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











