必须修改hosts文件将域名解析至127.0.0.1,Windows用管理员权限编辑C:\Windows\System32\drivers\etc\hosts添加“127.0.0.1 test.local”,macOS/Linux执行sudo nano /etc/hosts添加相同行,保存后运行ipconfig /flushdns或sudo dscacheutil -flushcache刷新DNS缓存。

hosts 文件怎么改才有效
ThinkPHP5 本地域名访问失败,90% 是因为 hosts 没生效,不是 ThinkPHP 配置问题。它只负责让浏览器把 test.local 解析成 127.0.0.1,不改这一步,后面全白搭。
- Windows:用管理员权限打开
C:\Windows\System32\drivers\etc\hosts,末尾加一行127.0.0.1 test.local,保存时选“所有文件”类型、编码为 UTF-8 无 BOM - macOS/Linux:终端运行
sudo nano /etc/hosts,添加后按Ctrl+O → Enter → Ctrl+X - 改完必须清缓存:
ipconfig /flushdns(Win)或sudo dscacheutil -flushcache(macOS) - 别写
http://test.local或带端口如test.local:8000,hosts只认纯域名 + IP
Apache 虚拟主机 DocumentRoot 必须指向 public/ 目录
ThinkPHP5 的入口是 public/index.php,Web 服务器如果指向项目根目录(比如 /var/www/thinkphp),会导致 app/、config/ 等目录被直接暴露,或返回 403/404。
- 在
httpd-vhosts.conf中确认DocumentRoot和<directory></directory>路径都指向your_project_path/public - 必须开启
AllowOverride All,否则.htaccess不生效,URL 重写(隐藏index.php)会失效 - 示例配置片段:
<VirtualHost *:80> ServerName test.local DocumentRoot "/path/to/your/project/public" <Directory "/path/to/your/project/public"> AllowOverride All Require all granted </Directory> </VirtualHost> - 改完必须重启 Apache:
sudo apachectl graceful或sudo systemctl restart apache2
为什么开了 app.domain_bind 还是 404
app.domain_bind 是运行时校验,不是域名映射手段。它只在请求进来后比对 $_SERVER['HTTP_HOST'],不匹配就直接抛出 404 —— 它防的是别人用 IP 或错域名访问你,不是帮你把域名连进来。
- 检查实际请求的 Host:
var_dump($_SERVER['HTTP_HOST'] ?? 'no host');,输出必须和app.domain_bind数组里字符串完全一致 - 常见不一致点:
test.localvstest.local:80(端口)、test.localvswww.test.local(子域)、http://test.local(协议头不该出现在 Host 中) - 本地开发建议先留空
'domain_bind' => []或设为['test.local'],等 Web 服务器确认能进来了再开
Nginx 的 root 和 try_files 写错就 404
Nginx 没有 .htaccess,所有路由逻辑靠配置驱动。如果 root 指向错误,或漏了 try_files,ThinkPHP5 的伪静态 URL(如 /index/index)必然 404。
立即学习“PHP免费学习笔记(深入)”;
-
root必须是绝对路径,且结尾不带斜杠:root /path/to/your/project/public; - 必须保留 ThinkPHP 官方推荐的
try_files规则:try_files $uri $uri/ /index.php?$query_string; - 别漏掉
index index.php;,否则访问根路径可能返回 403 - 配置完务必验证语法:
nginx -t,再重载:sudo nginx -s reload
/public、端口没对齐,都会卡在 404。调试时优先用 curl -v http://test.local 看响应头里的 Host 是什么,比猜快得多。



















