phpsymfonyroutessubdomain

Redirect domain and subdomain in SF2


I have followed the tuts from the knpUniversity "How to handle dynamic sub domains in symfony2" .Routing the sub domain works but when i try to go to www.domain.com i get the error that i have thrown if sub domain is not found. How to fix this? Here is my code:

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

Solution

  • I dont know if this is the best way to do this but I have made it work.

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