Routing in Yii2 is responsible for processing incoming requests and mapping them to the appropriate controllers and actions. Yii2 provides a flexible and powerful routing system, allowing clean URLs (Pretty URLs) and custom route configurations. In this tutorial, we will cover:
Url::to() and Url::toRoute()In Yii2, routing is managed by the urlManager component. When a user visits a URL, Yii2 processes the request and determines which controller and action should handle it.
For example, visiting:
http://yourwebsite.com/index.php?r=site/aboutMaps to:
SiteController (controllers/SiteController.php)actionAbout()By default, Yii2 uses query parameters (?r=controller/action). To improve readability, we enable Pretty URLs.
Pretty URLs remove the ?r= parameter, making URLs more user-friendly.
config/web.php (Basic Template)'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
// Define custom rules here
],
],
],enablePrettyUrl → Enables clean URLsshowScriptName → Hides index.php from URLsModify frontend/config/main.php and backend/config/main.php in the same way.
Custom routes allow defining user-friendly URLs. Add route rules inside urlManager['rules'].
'rules' => [
'about-us' => 'site/about', // Maps "about-us" to "site/about"
'contact' => 'site/contact', // Maps "contact" to "site/contact"
]Now,
http://yourwebsite.com/about-usRoutes can include dynamic parameters. Example:
'rules' => [
'post/<id:\d+>' => 'post/view', // Maps "post/123" to "post/view?id=123"
],Here, \d+ ensures only numeric values are accepted.
If a user visits:
http://yourwebsite.com/post/5It will be mapped to:
http://yourwebsite.com/index.php?r=post/view&id=5Without the ?id=5 query string.
Url::to()When creating links in Yii2, use Url::to():
use yii\helpers\Url;
<a href="<?= Url::to(['site/about']) ?>">About</a>This ensures URLs are generated correctly, even if route structures change.
For dynamic parameters:
<?= Url::to(['post/view', 'id' => 5]) ?>Generates /post/5 when Pretty URLs are enabled.
Modules are like mini-applications within Yii2. If you're using modules, you need to set up routing correctly.
Modify config/web.php to register modules:
'modules' => [
'admin' => [
'class' => 'app\modules\admin\Module',
],
],Here, we register an admin module located at modules/admin/Module.php.
By default, Yii2 maps module routes as:
http://yourwebsite.com/index.php?r=admin/default/indexWhich means:
adminDefaultController (modules/admin/controllers/DefaultController.php)actionIndex()If Pretty URLs are enabled, visiting:
http://yourwebsite.com/adminWill map to admin/default/index.
Modify config/web.php inside urlManager:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'admin' => 'admin/default/index',
'admin/<controller>/<action>' => 'admin/<controller>/<action>',
],
],Now,
Will map to:
adminUserController (modules/admin/controllers/UserController.php)actionList()Inside your views or controllers, generate module URLs like this:
<?= Url::to(['/admin/user/list']) ?>This will generate:
http://yourwebsite.com/admin/user/listUrl::to() and Url::toRoute()Yii2 provides two primary methods for generating URLs dynamically:
Url::to()The Url::to() function is useful when generating absolute and relative URLs.
use yii\helpers\Url;
echo Url::to(['site/about']); This will generate:
/index.php?r=site/aboutOr, if Pretty URLs are enabled:
/site/aboutecho Url::to(['post/view', 'id' => 10]);This will generate:
/post/view?id=10Or with Pretty URLs:
/post/10echo Url::to(['site/about'], true);Generates:
http://yourwebsite.com/site/aboutUrl::toRoute() (Why It’s Important!)Url::toRoute() is more flexible and ensures the URL is generated relative to the current module and controller.
echo Url::toRoute(['site/about']);This works similarly to Url::to() but is useful in modular applications.
If you're inside a module and use Url::to(), it may not correctly generate module-specific routes. Instead, use Url::toRoute():
echo Url::toRoute(['/admin/user/list']);This ensures it correctly generates the module-based URL:
http://yourwebsite.com/admin/user/listUrl::to() and Url::toRoute()| Feature | Url::to() | Url::toRoute() |
|---|---|---|
| Generates absolute URL | (when true passed) | No |
| Works with module-specific routes | No | Yes |
| Good for general URLs | Yes | Yes |
| Good for module-based routing | No | Yes |
| Uses current module & controller | No | Yes |
If a route is not found, Yii2 automatically shows a 404 error. To customize this, modify views/site/error.php.
<h1><?= $name ?></h1>
<p><?= nl2br(Html::encode($message)) ?></p>You can also log undefined routes by customizing errorHandler.
Clear Cache: Run
php yii cache/flush-allCheck .htaccess (For Apache)
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.phpRestart Web Server (For Nginx/Apache)
Yii2 routing system provides flexibility to define clean and SEO-friendly URLs. We covered:
Url::to()Url::to() and Url::toRoute()Now, your Yii2 app will have professional and user-friendly URLs. In the next tutorial, we will explore Yii2 Controllers & Actions!
Sign in to join the discussion and post comments.
Sign in