Files
tp/app/common/middleware/DomainParse.php
T

69 lines
2.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\common\middleware;
use think\facade\Db;
use think\Request;
/**
* 域名解析中间件
* 通过访问域名自动识别租户
*/
class DomainParse
{
public function handle(Request $request, \Closure $next)
{
$host = $request->host(true); // 获取完整域名,不带端口
// 你的后台/平台域名(排除,不走租户逻辑)
$adminDomains = ['back.yunzer.cn', 'api.yunzer.cn'];
$platformDomains = ['www.yunzer.cn', 'yunzer.cn'];
// 后台/平台/API域名,直接放行
if (in_array($host, $adminDomains) || in_array($host, $platformDomains)) {
return $next($request);
}
// 解析域名(兼容 yunzer.com.cn/dh2.fun
$domainParts = explode('.', $host);
$allowMainDomains = ['yunzer.com.cn', 'dh2.fun'];
$mainDomain = '';
foreach ($allowMainDomains as $domain) {
$domainLen = count(explode('.', $domain));
$currentLen = count($domainParts);
if ($currentLen > $domainLen) {
$matchMain = implode('.', array_slice($domainParts, -$domainLen));
if ($matchMain === $domain) {
$mainDomain = $matchMain;
break;
}
}
}
// 非租户主域名,放行(走API默认界面,可改为跳转到平台)
if (empty($mainDomain)) {
return $next($request);
}
// 查询租户域名绑定记录
$tenantDomain = Db::name('mete_tenant_domain')
->where('full_domain', $host)
->where('status', 1)
->find();
if ($tenantDomain) {
// 1. 写入租户ID到请求(核心,后续所有逻辑都能获取)
$request->tenantId = $tenantDomain['tid'];
$request->header('X-Tenant-Id', (string)$tenantDomain['tid']);
// 2. 额外:写入租户域名信息,方便模板使用
$request->tenantDomain = $host;
$request->tenantMainDomain = $mainDomain;
}
return $next($request);
}
}