快速总结
- 您需要在 DNS 服务器上创建通配符域
*.website.example
- Then in your vhost container you will need to specify the wildcard as well
*.website.example
- This is done in the ServerAlias DOCs
- 然后在PHP中提取并验证子域并显示相应的数据
长版
1. 创建通配符 DNS 条目
在您的 DNS 设置中,您需要创建一个通配符域条目例如*.example.org
。通配符条目如下所示:
*.example.org. 3600 A 127.0.0.1
2. 在vhost中包含通配符
Next up in the Apache configuration you need to set up a vhost container that specifies the wildcard in the ServerAlias DOCs directive. An example vhost container:
<VirtualHost *:80>
ServerName server.example.org
ServerAlias *.example.org
UseCanonicalName Off
</VirtualHost>
3. 找出您所在的 PHP 子域
然后在 PHP 脚本中,您可以通过查看来找到域$_SERVER
超级全局变量。下面是 PHP 中抓取子域名的示例:
preg_match('/([^.]+)\.example\.org/', $_SERVER['SERVER_NAME'], $matches);
if(isset($matches[1])) {
$subdomain = $matches[1];
}
我在这里使用了正则表达式,以允许人们通过以下方式访问您的网站www.subdomain.example.org
or subdomain.example.org
.
如果您从未预料到必须处理 www. (或其他子域)那么您可以简单地使用子字符串,如下所示:
$subdomain = substr(
$_SERVER['SERVER_NAME'], 0,
strpos($_SERVER['SERVER_NAME'], '.')
);
海量虚拟主机
大规模虚拟主机与上述方案略有不同,因为您通常会使用它来托管许多不同的网站,而不是像问题所建议的那样尝试使用它来为应用程序提供动力。
我之前已经记录了基于 mod_rewrite 的海量虚拟主机环境在我的博客上发帖,如果这是您想要走的路线,您可以查看该路线。当然,还有各自的 Apache 手册页.
Apache 还有一种处理大规模虚拟主机的内部方法,该方法比我使用的 mod_rewrite 方法稍微不太灵活。 Apache 上对此都有描述动态配置的海量虚拟主机手册页.