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); } }