Search code examples
phproutesyii2url-routingyii-url-manager

Yiii2 subdomain in url manager not working


I have a Yii2 advanced project. I have MyCompanyController.php in the frontend controllers and I want to add a subdomain to this controller so I did this :

    'urlManager' => [
        'rules' => [
            '/' => 'site/index',
            'http://co.example.com' => 'my-company/index', // Not work :-(
            'http://co.example.com/<action>' => 'my-company/<action>',
             ...
        ]
     ]

Now this code is working perfectly and when I open http://co.example.com/index my index action gets rendered, But when I open http://co.example.com without mentioning the action it is not working and it calls the site controller's index action instead .


Solution

  • The reason is the order of the url rules.

    I suspect the application is called with another URL like http://example.com or http://bla.example.com or what is the / rule for?

    As it seems / is sufficient for any URL that has no path component, so second rule doesn't get evaluated. You could either prepend the protocol and domain path like 'http://example.com/' => 'site/index' (so the other (suspected) domain is explicitly declared and this rule won't match if http://co.example.com is called) or just remove this rule (if site/index shouldn't be called at all).

    Note that if no rule matches the defaultRoute of the application will be used.

    From the Yii2 Guide:

    ... to parse an incoming request, the URL manager examines the rules in the order they are declared and looks for the first rule that matches the requested URL.

    [...]

    When parsing or creating URLs, URL manager examines URL rules in the order they are declared. Therefore, you may consider adjusting the order of the URL rules so that more specific and/or more commonly used rules are placed before less used ones.

    See also the Yii2 Guide about Rules with Server Names.