简体   繁体   中英

Yii2 - Get an app URL without params

I have no idea how to get a full url to my app web folder in Yii2. The following rules:

<?=Yii::$app->getUrlManager()->getBaseUrl();?><br>
<?=Yii::$app->homeUrl;?><br>
<?=Yii::$app->getHomeUrl();?><br>
<?=Yii::$app->request->url;?><br>
<?=Yii::$app->request->absoluteUrl;?><br>
<?=Yii::$app->request->baseUrl;?><br>
<?=Yii::$app->request->scriptUrl;?><br>
<?=Url::to();?><br>
<?=Url::to(['site/index']);?><br>
<?=Url::base();?><br>
<?=Url::home();?><br>
<?=Yii::$app->getUrlManager()->getBaseUrl();?><br>

returns:

/yiiapp/web
/yiiapp/web/
/yiiapp/web/
/yiiapp/web/en/reset-password-request
http://website.com/yiiapp/web/en/reset-password-request
/yiiapp/web
/yiiapp/web/index.php
/yiiapp/web/en/reset-password-request
/yiiapp/web/site/index
/yiiapp/web
/yiiapp/web/
/yiiapp/web

when I need to get the (absoluteUrl is the closest one here):

http://website.com/yiiapp/web

I could probably combine one of the results with some $_SERVER var… but is it a solution?

I realize this post is quite old but I want to answer it anyway. To get a full URL to your app web folder in Yii2 you can try these three options:

  1. Url::to('@web/', ''); returns //website.com/yiiapp/web/
  2. Url::to('@web/', true); returns http://website.com/yiiapp/web/
  3. Url::to('@web/', 'https'); returns https://website.com/yiiapp/web/

You can use Yii::$app->getUrlManager()->createAbsoluteUrl() method or yii\\helpers\\Url::toRoute() to generate absolute urls. yii\\helpers\\Url::to() also can be used look at the documentation. Eg <?=Url::to(['site/index'], true);?> should output http://website.com/yiiapp/web/site/index . If you need to get root url to your app, try \\yii\\helpers\\Url::to('/', true);

There are multiple ways to achieve this, but probably the most clean way to get base URL of your app is to use Url::base() :

Url::base(true);

Most of methods in Url helper allows to you specify $scheme argument - you should use it if you want to create absolute URL (with domain).

The URI scheme to use in the returned base URL:

  • false (default): returning the base URL without host info.
  • true : returning an absolute base URL whose scheme is the same as that in yii\\web\\UrlManager::$hostInfo.
  • string : returning an absolute base URL with the specified scheme (either http , https or empty string for protocol-relative URL).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM