修改 hosts 文件是第一步,因为本地绑定域名本质是绕过 DNS 查询,让系统将域名直接解析到 127.0.0.1 或 ::1;不修改则浏览器无法将请求发往本地 PHP 服务。
hosts 文件是第一步本地绑定域名本质是绕过 DNS 查询,让系统把某个域名直接解析到 127.0.0.1 或 ::1。不改 hosts,浏览器根本不会把请求发到你本地的 PHP 服务。
Windows 路径:C:\Windows\System32\drivers\etc\hosts
macOS / Linux 路径:/etc/hosts
127.0.0.1 myapp.test
http://,也不加端口(127.0.0.1:8000 myapp.t
est 无效)ping myapp.test,看到回复 127.0.0.1 才算生效PHP 7.4+ 的 php -S 默认只监听 127.0.0.1:8000,且不处理 Host 头校验——这意味着只要 hosts 指向正确,它就能响应 myapp.test 的请求,但需显式绑定地址。
0.0.0.0:8000 或 [::]:8000 启动,否则仅响应 localhost 或 127.0.0.1
php -S 0.0.0.0:8000 router.php
router.php 需存在,哪怕只写 ,否则启动报错
http://myapp.test:8000 即可,无需额外配置和内置服务器不同,Apache/Nginx 是真正按 Host 头分发请求的,必须显式配置虚拟主机(VirtualHost),否则会落到默认站点或 404。
httpd.conf 或 apache2.conf 中启用了 vhost_alias 模块,并在 httpd-vhosts.conf 中添加:ServerName myapp.test DocumentRoot "/path/to/your/php/project" AllowOverride All Require all granted
nginx.conf 或站点配置文件中写:server {
listen 80;
server_name myapp.test;
root /path/to/your/php/project;
index index.php;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000; # 或 unix socket
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}}
sudo apachectl restart 或 sudo nginx -s reload
绑定域名后打不开,大概率不是 PHP 问题,而是网络层或服务层卡住了。
ERR_CONNECTION_REFUSED:PHP 服务根本没运行,或端口被占用;检查 lsof -i :8000(macOS/Linux)或 netstat -ano | findstr :8000(Windows)ERR_CONNECTION_TIMED_OUT:hosts 没生效,或防火墙拦截了端口;确认 ping myapp.test 回复的是 127.0.0.1
403 Forbidden:Web 服务器拒绝读取目录,常见于 Apache 的 Require all denied 默认策略,或 Nginx 的 root 路径权限不足404 Not Found:路由没匹配上,尤其用 PHP 内置服务器时,router.php 返回 false 会触发 404;检查是否漏写了该文件,或逻辑返回了 false
最易忽略的是:改了 hosts 和配置,却忘了清浏览器 DNS 缓存(Chrome 地址栏输 chrome://net-internals/#dns 点 Clear host cache)。