Answer a question

I want to handle dynamic subdomain in my Symfony 4 application.

I'm looking for configuration like this:

  • store1.domain.com => StoreController::index
  • store2.domain.com => StoreController::index
  • www.domain.com => HomeController::homePage
  • domain.com => HomeController::homePage etc etc.

I'm trying this code but is not working. Its always match with HomeController. StoreController never matching.

And when I try this configuration "domain.com" request show to me "Welcome to nginx!" page.

class StoreController extends AbstractController
{
    /**
     * @Route("/", name="store_home", host="{store_name}.domain.test")
     */
    public function storeHomepage()
    {
        return $this->render('store/index.html.twig');
    }
}

class HomeController extends AbstractController
{
    /**
     * @Route("/", name="site_home")
     */
    public function homePage()
    {
        return $this->render('site/home/index.html.twig');
    }
}

And here is my nginx configuration:

server {
    listen       80;
    server_name  *.domain.test;
    root       /site/root/public;

    location config bla bla bla;
}

Answers

I'm trying this code but is not working. Its always match with HomeController. StoreController never matching.

You are using annotation routing, so the routes are loaded alphabetically.

Your home controller will be tried first, and it will match, because you have not put any restrictions on it.

Try explicitly setting the host.

class HomeController extends AbstractController
{
    /**
     * @Route("/", name="site_home", host="domain.test")
     */
    public function homePage()
    {
        return $this->render('site/home/index.html.twig');
    }
}

And when I try this configuration "domain.com" request show to me "Welcome to nginx!" page.

I'm not really an nginx expert, but I believe that server_name *.domain.test; means all subdomains, but exludes the main domain. Try it as server_name .domain.test;

Logo

开发云社区提供前沿行业资讯和优质的学习知识,同时提供优质稳定、价格优惠的云主机、数据库、网络、云储存等云服务产品

更多推荐