Search code examples
symfonywildcard-subdomainsymfony-routing

How to move slug to subdomain in Symfony3


I have a web-app where every User has his own personalized link

https://app.myapp.com/{uuid}/frontpage

Where uuid indicates User resource loaded from the database.

And now, the idea is to move /{uuid}/ to subdomain, so it should look as follows:

https://{uuid}.myapp.com/frontpage

While I have created wildcard DNS and can extract subdomain in Symfony's Controllers easily, the problem is now how to tell Symfony that uuid should be taken from subdomain now.

In Controllers I have routing defined as follows

/**
 * @Route("/{uuid}/frontpage", name="frontpage")
 * @ParamConverter("user", class="AppBundle:User", converter="converter.user")
 * @Template("FrontPage.html.twig")
 */
public function indexAction(Request $request, User $user)
{

}

I would like to avoid rewriting all Controllers and strip out /{uuid}/ part because I have hundreds of Controllers defined like that.

Is there a way to manage this maybe via Listeners?


Solution

  • With Symfony 3, you can match a route based on the host. And basically you can also "placeholderize" your subdomain and get the related value in your HttpFoundation\Request object (in your controller for instance).

    Ex. :

    mobile_homepage:
    path:     /
    host:     "{subdomain}.example.com"
    defaults:
        _controller: AppBundle:Main:mobileHomepage
        subdomain: m
    

    https://symfony.com/doc/current/routing/hostname_pattern.html