泛解析php实现
泛解析PHP实现方法
泛解析(Wildcard DNS)允许通过通配符(如*.example.com)匹配所有子域名,并将请求指向同一服务器。以下是PHP实现的常见方法:
获取当前子域名
通过解析$_SERVER['HTTP_HOST']获取子域名:
$host = $_SERVER['HTTP_HOST'];
$subdomain = str_replace('.example.com', '', $host);
动态路由处理
根据子域名加载不同内容或配置:
$validSubdomains = ['blog', 'shop', 'support'];
if (in_array($subdomain, $validSubdomains)) {
include("$subdomain/index.php");
} else {
header("HTTP/1.0 404 Not Found");
exit;
}
数据库驱动泛解析
将子域名与数据库记录关联:
$pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
$stmt = $pdo->prepare('SELECT * FROM tenants WHERE subdomain = ?');
$stmt->execute([$subdomain]);
$tenant = $stmt->fetch();
if ($tenant) {
define('TENANT_CONFIG', $tenant['config']);
} else {
header("Location: https://example.com/404");
}
虚拟主机配置示例(Apache)
确保服务器配置支持泛解析:
<VirtualHost *:80>
ServerName example.com
ServerAlias *.example.com
DocumentRoot /var/www/wildcard
</VirtualHost>
Nginx配置示例
server {
listen 80;
server_name ~^(?<subdomain>.+)\.example\.com$;
root /var/www/wildcard/$subdomain;
}
注意事项
- DNS需设置泛解析记录(如
*.example.com A 1.2.3.4) - 避免开放过多未验证子域名导致安全风险
- 考虑缓存子域名解析结果提升性能
- 多租户场景需隔离数据存储路径
完整示例代码
$subdomain = explode('.', $_SERVER['HTTP_HOST'])[0];
$configFile = __DIR__ . "/configs/$subdomain.php";
if (file_exists($configFile)) {
require $configFile;
$router->dispatch("/{$_SERVER['REQUEST_URI']}");
} else {
http_response_code(404);
echo "Subdomain not configured";
}






