phpenv 不支持泛域名解析,需 hosts 文件逐条添加、Web 服务器配置 ServerAlias 或 server_name 通配、PHP 层安全提取子域名并业务分发。

phpenv 本身不处理域名解析,它只是 PHP 版本管理工具,二级域名和泛解析必须靠系统 hosts + Web 服务器(Apache/Nginx)+ PHP 应用层协同完成。直接改 phpenv 配置无法实现泛域名访问。
本地 hosts 文件怎么加多行二级域名
Windows 路径是 C:\Windows\System32\drivers\etc\hosts,macOS/Linux 是 /etc/hosts。不能写 *.test.com 这种通配符 —— 系统 hosts 不支持,必须逐条添加:
127.0.0.1 a.test.com127.0.0.1 b.test.com127.0.0.1 shop.test.com127.0.0.1 api.test.com
保存后无需重启,但浏览器可能缓存 DNS,可执行 ping a.test.com 验证是否解析到 127.0.0.1;若失败,试试 ipconfig /flushdns(Windows)或 sudo dscacheutil -flushcache(macOS)。
Apache 虚拟主机必须用 ServerAlias 支持泛匹配
在 httpd-vhosts.conf 里,不能只写 ServerName test.com,否则 a.test.com 会 404 或落到默认站点。正确写法是:
立即学习“PHP免费学习笔记(深入)”;
<VirtualHost *:80>
DocumentRoot "/path/to/your/project"
ServerName test.com
ServerAlias *.test.com
<Directory "/path/to/your/project">
Require all granted
AllowOverride All
</Directory>
</VirtualHost>
注意点:
-
ServerAlias *.test.com是关键,Apache 会把所有子域名都路由到这里 - 确保
httpd.conf中已启用Include conf/extra/httpd-vhosts.conf - 修改后必须运行
apachectl configtest(或httpd -t)验证语法,再sudo apachectl restart
PHP 里怎么安全提取子域名(别踩 explode('.').[0] 的坑)
explode('.', $_SERVER['HTTP_HOST'])[0] 在 www.test.com 或 api.v2.test.com 场景下会出错 —— 前者取到 www,后者取到 api,但你真正想识别的可能是 v2 或主域逻辑。推荐用更健壮的方式:
- 先定义主域:$mainDomain = 'test.com';
- 用
str_ends_with($_SERVER['HTTP_HOST'], '.' . $mainDomain)判断是否为子域名 - 再截取前缀:
$sub = substr($_SERVER['HTTP_HOST'], 0, -strlen('.' . $mainDomain)) - 对
www、admin等保留子域做白名单过滤,避免误判
ThinkPHP 用户注意:Request::subDomain() 返回空字符串而非 null,判断要用 === '',不是 === null;且必须配合 Route::domain('*') 才能进泛域路由分组。
Nginx 下泛域名配置比 Apache 更严格
如果你用的是 Nginx(比如通过 phpstudy、laragon 或手动部署),server_name 必须显式支持通配符,且有顺序限制:
- 写成
server_name *.test.com;只匹配一级子域(a.test.com✅,a.b.test.com❌) - 要支持多级,得加
server_name ~^(?<sub>.+)\.test\.com$;</sub>并在 location 中用$sub变量传参 - HTTPS 环境下,如果用了反向代理(如 Cloudflare、Nginx SSL 终止),原始
Host头可能被覆盖,需确认fastcgi_param HTTP_HOST $host;是否透传
最易忽略的是:泛域名生效 ≠ 子域名自动路由到对应模块。PHP 层仍需主动解析 $_SERVER['HTTP_HOST'],并做业务分发 —— 没有框架能替你决定 shop.test.com 该显示商城页还是后台页。



















