Changes
Title
changed
Yii2 - How to make UrlManager createAbsoluteUrl work with sub-domains
Category
unchanged
How-tos
Yii version
changed
2.0
Tags
changed
yii2, url manager, urlmanager, URL, subdomain, domain,sub-domains, domainyii2,url manager,urlmanager
Content
changed
[...]
So in this guide, I am going to show you the best and only way I found to create links to another one of your Yii apps (ie: backend or frontend) that are on a sub-domain.
---
### My method for handling sub-domains
Unfortunately, there isn't an accurate and reliable way to grab only the domain name. A bunch of regex or stripping, or pulling from a huge list of valid domain extensions, etc. Nothing you want running on a site with tons of users, it will create a bottle neck real quick. Yeah, you could implement caching and you should for large volume sites. However, I prefer to cache lean efficient code instead of using caching to save my rear on terrible logic.[...]
`common/config/bootstrap.php`
~~~
```php
// URL Manager Aliases
Yii::setAlias('@domainName', (YII_ENV === 'dev') ? 'yii2-members-system.dev' : 'yourlivesite.com');
Yii::setAlias('@frontendSubdomain', 'users');
Yii::setAlias('@backendSubdomain', 'admin');
~~~```
Create `common/components/UrlManager.php`
~~~
```php
<?php
namespace common\components;[...]
}
~~~```
Now in whichever app your needing to link to another subdomain, you need to edit it's main config. So if in backend you need to link to frontend (or mainsite needs to link to frontend as in my members system), then edit your backend config.[...]
Add this to your config under the components array:
~~~```php
'urlManagerFrontend' => [
'class' => 'common\components\UrlManager',[...]
],
],
~~~```
Now, wherever you need to create a link (or get the url for any reason) use CreateAbsoluteUrl inside the new UrlManager like so:
~~~```
Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/login'])
~~~```
In my app, it generates a link for my mainsite to the users app: `http://users.yii2-members-system.dev/site/login`. This was so on my mainsite I can link to the user's subdomain for them to login.
I hope this helps someone, and I hope Yii actually adopts a solution for this sort of linking and handling sub-domains.