Manejando multi subdominios en Symfony

Aplicaciones de multi subdominios

Manos a la Obra

1. Configurando el routing

resource: "routing/routing.yml"
host: "{subdomain}.%base_domain%"
subdomain: %default_media%
enviroment: dev

Definiendo el VirtualHost

<VirtualHost *:80>  ServerName
ServerAlias *
DocumentRoot "/home/user/sites/site/web"
<Directory "/home/user/sites/site/web">
AllowOverride All
Allow from All

Configurando el routing


Definiendo el EventListener

namespace AppBundle\Event;
use AppBundle\Entity\Media;
use AppBundle\Entity\MediaManager;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestListener implements EventSubscriberInterface
* @var MediaManager
private $mediaManager;
* @var string
private $enviroment;
* @var Router
private $router;
* @var EntityManager
private $em;
public function __construct(MediaManager $mediaManager, $enviroment, Router $router, EntityManager $em)
$this->mediaManager = $mediaManager;
$this->enviroment = $enviroment;
$this->router = $router;
$this->em = $em;
public function onKernelRequest(GetResponseEvent $event)
$request = $event->getRequest();
$currentHost = $request->getHttpHost();
$baseHost = $this->container->getParameter("base_domain");
$explodeElements = explode('.', $currentHost);
$subdomain = $explodeElements[0];
$site = $this->em->getRepository(Media::class)->findOneBy(array(
'subdomain' => $subdomain
if (!$site) {
throw new NotFoundHttpException(sprintf('No site for host "%s", subdomain "%s"', $baseHost, $subdomain));
if (!$site->isActive()) {
throw new LogicException("Media is not active");
$this->router->getContext()->setParameter('subdomain', $subdomain);
$this->router->getContext()->setParameter("enviroment", $enviroment);
public static function getSubscribedEvents()
return array(
KernelEvents::REQUEST => array(





Full Stack Web Developer —

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adrián Alonso

Adrián Alonso

Full Stack Web Developer —

More from Medium

Lets Use Hashicorp Packer for creating LAMP Stack (Part 1 — Creating AWS AMI)

How Tokenization Can Change Asset Management

HTTP Security Headers