main-domain.tld -> main_contextmain-domain2.tld -> main_contextservice.main-domain.tld -> service_contextservice.main-domain2.tld -> service_contextservice.maybe-several-other-brand-domains.tld -> service_contextadmin.main-domain.tld -> admin_contextadmin.main-domain2.tld -> admin_contextadmin.maybe-several-other-brand-domains.tld -> admin_context
在只有一个域名的情况下,我们可以使用以下方式将控制器分配给特定的上下文:```php#[Route( path: '/', requirements: ['domain' => '%app.public_hostname_context1%'], defaults: ['domain' => '%app.public_hostname_context1%'], host: '{domain}',)]登录后复制
其中 app.public_hostname_context1 是在 .env.local 文件中配置的主机名。
当需要支持多个域名时,defaults 配置无法访问当前主机名,因此需要在生成 URL 时显式设置域名。
解决方案:使用 RequestListener 设置默认域名
一种解决方案是移除路由定义中的 defaults,并为每个上下文的有效域名提供一个模式。
#[Route( path: '/', requirements: ['domain' => '%app.public_hostnames_context1_pattern%'], host: '{domain}',)]登录后复制
app.public_hostnames_context1_pattern 是在 .env.local 文件中配置的模式,包含该上下文的所有可能主机名,例如:
PUBLIC_HOSTNAME_CONTEXT1_PATTERN=(?:service\.main-domain\.tld|service\.main-domain2\.tld)登录后复制
为了为所有路由的 domain 参数设置当前主机名作为默认值,我们可以创建一个 RequestListener,并在 RouterListener 之前执行它。
1. 配置 services.yaml:
services: # 必须在 RouterListener (优先级 32) 之前调用,以加载域名 App\EventListener\RequestListener: tags: - { name: kernel.event_listener, event: kernel.request, priority: 33 }登录后复制
2. 创建 RequestListener:

表格形态的AI工作流搭建工具,支持批量化的AI创作与分析任务,接入DeepSeek R1满血版


<?phpdeclare(strict_types=1);namespace App\EventListener;use Symfony\Component\HttpKernel\Event\RequestEvent;use Symfony\Component\Routing\RouterInterface;class RequestListener{ public function __construct( private RouterInterface $router, ){} public function onKernelRequest(RequestEvent $event) { if (false === $this->router->getContext()->hasParameter('domain')) { $this->router->getContext()->setParameter('domain', $event->getRequest()->getHost()); } }}登录后复制
这段代码的作用是,如果路由上下文中没有 domain 参数,则将当前请求的主机名设置为 domain 参数的值。
优点和缺点
优点:
可以灵活地覆盖 domain 参数,以便在生成 URL 时指定域名。缺点:
如果为另一个上下文生成 URL 时没有显式设置域名,则会引发错误,因为当前请求的主机名可能不符合该上下文的域名模式。总结
通过使用 RequestListener,我们可以方便地为 Symfony 路由中的 domain 参数设置默认值,从而支持多个动态主机。虽然存在一些潜在的缺点,但这种解决方案可以满足大多数多域名应用的需求。在使用时,需要注意在生成跨上下文的 URL 时显式设置域名,以避免出现错误。
登录后复制以上就是支持 Symfony 路由中的多个动态主机的详细内容,更多请关注php中文网其它相关文章!