重定向 SF2 中的域和子域

Redirect domain and subdomain in SF2

我遵循了 knpUniversity "How to handle dynamic sub domains in symfony2" 的 tuts。路由子域有效,但是当我尝试转到 www.domain.com 时,我得到了如果找不到子域我抛出的错误.如何解决这个问题? 这是我的代码:

public function onKernelRequest(GetResponseEvent $getResponseEvent)
{
    $request = $getResponseEvent->getRequest();
    $host = $request->getHost();
    $base_host = $this->baseHost;
    $sub_domain = str_replace('.'.$base_host,'',$host);
    $site = $this->em->getRepository('AppBundle:Client')->findOneBy(['subDomain' => $sub_domain]);

    if(!$site){
        throw new NotFoundHttpException(sprintf(
            'Cannot find site for host "%s", subdomain "%s"  ',
            $host,
            $sub_domain
        ));
    }

    $siteManager = $this->siteManager;
    $siteManager->setCurrentSite($site);
}

我不知道这是否是最好的方法,但我已经成功了。

public function onKernelRequest(GetResponseEvent $getResponseEvent)
{
    $request = $getResponseEvent->getRequest();
    $host = $request->getHost();
    $base_host = $this->baseHost;
    $sub_domain = str_replace('.'.$base_host,'',$host);
    $site = $this->em->getRepository('AppBundle:Client')->findOneBy(['subDomain' => $sub_domain]);

    if(!$site && $base_host != $sub_domain){
        throw new NotFoundHttpException(sprintf(
            'Cannot find site for host "%s", subdomain "%s"  ',
            $host,
            $sub_domain
        ));
    }

    $siteManager = $this->siteManager;
    $siteManager->setCurrentSite($site);
}