symfonyroutessymfony4

Configure a default host for routes in Symfony 4


So far my Symfony app was hosting a single domain. Now, I need to host a few pages on another domain. For business reasons, this must appear as a separate domain to the user, even though it actually belongs to the same app.

Say my app is hosted on example1.com. I need to host some pages on example2.com.

So I created a new controller:

class NewsletterController extends AbstractController
{
    /**
     * @Route("/unsubscribe", name="newsletter_unsubscribe", host="example2.com")
     */
    public function unsubscribe(): Response
    {
        return $this->render('newsletter/unsubscribe.html.twig');
    }
}

This works fine; the page is served correctly, and the /unsubscribe path in only routed when requested on example2.com. On example1.com, it returns a 404 as expected.

The issue is, now all routes intended to be matched on the main domain example1.com, are also matched on example2.com, which is not what I want.

Of course, I could change all other @Route annotations to include host="example1.com", but this is cumbersome and prone to mistakes in the future.

Is there a way to require a host for all routes by default, unless overridden in the @Route annotation?


Solution

  • It's not a final solution but it can help...

    You can set the @Route annotation to each controller class and separate your controllers for each domain...

    /**
     * @Route(host="example2.com")
     */
    class NewsletterController extends AbstractController
    {
        /**
         * @Route("/unsubscribe", name="newsletter_unsubscribe")
         */
        public function unsubscribe(): Response
        {
            return $this->render('newsletter/unsubscribe.html.twig');
        }
    }
    

    We will find a better solution soon :)