Routing & Pretty URLs in Yii2

Introduction

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:

  • How Yii2 handles routing
  • Enabling Pretty URLs
  • Customizing routes
  • Using parameterized routes
  • Creating URL rules
  • Routing for Yii2 Modules
  • Generating URLs using Url::to() and Url::toRoute()

1. Understanding Routing in Yii2

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/about

Maps to:

  • Controller: SiteController (controllers/SiteController.php)
  • Action: actionAbout()

By default, Yii2 uses query parameters (?r=controller/action). To improve readability, we enable Pretty URLs.


2. Enabling Pretty URLs

Pretty URLs remove the ?r= parameter, making URLs more user-friendly.

Step 1: Modify config/web.php (Basic Template)

'components' => [
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            // Define custom rules here
        ],
    ],
],
  • enablePrettyUrl → Enables clean URLs
  • showScriptName → Hides index.php from URLs

For Advanced Template

Modify frontend/config/main.php and backend/config/main.php in the same way.


3. Creating Custom Routes

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-us

4. Using Parameterized Routes

Routes 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/5

It will be mapped to:

http://yourwebsite.com/index.php?r=post/view&id=5

Without the ?id=5 query string.


5. Generating URLs Using 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.


6. Routing for Yii2 Modules

Modules are like mini-applications within Yii2. If you're using modules, you need to set up routing correctly.

Step 1: Define Modules in Configuration

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.

Step 2: Accessing Module Routes

By default, Yii2 maps module routes as:

http://yourwebsite.com/index.php?r=admin/default/index

Which means:

  • Module: admin
  • Controller: DefaultController (modules/admin/controllers/DefaultController.php)
  • Action: actionIndex()

If Pretty URLs are enabled, visiting:

http://yourwebsite.com/admin

Will map to admin/default/index.

Step 3: Custom Pretty URLs for Modules

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:

  • Module: admin
  • Controller: UserController (modules/admin/controllers/UserController.php)
  • Action: actionList()

Step 4: Generating URLs for Modules

Inside your views or controllers, generate module URLs like this:

<?= Url::to(['/admin/user/list']) ?>

This will generate:

http://yourwebsite.com/admin/user/list

7. Generating URLs Using Url::to() and Url::toRoute()

Yii2 provides two primary methods for generating URLs dynamically:

7.1 Using Url::to()

The Url::to() function is useful when generating absolute and relative URLs.

Basic Example

use yii\helpers\Url;
echo Url::to(['site/about']);  

This will generate:

/index.php?r=site/about

Or, if Pretty URLs are enabled:

/site/about

Generating URLs with Parameters

echo Url::to(['post/view', 'id' => 10]);

This will generate:

/post/view?id=10

Or with Pretty URLs:

/post/10

Generating Absolute URLs

echo Url::to(['site/about'], true);

Generates:

http://yourwebsite.com/site/about

7.2 Using Url::toRoute() (Why It’s Important!)

Url::toRoute() is more flexible and ensures the URL is generated relative to the current module and controller.

Basic Example

echo Url::toRoute(['site/about']);

This works similarly to Url::to() but is useful in modular applications.

Generating URLs Within Modules

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/list

Key Differences Between Url::to() and Url::toRoute()

FeatureUrl::to()Url::toRoute()
Generates absolute URL (when true passed)No
Works with module-specific routesNoYes
Good for general URLsYesYes
Good for module-based routingNoYes
Uses current module & controllerNoYes

8. Handling 404 Errors for Undefined Routes

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.


9. Testing and Verifying Pretty URLs

Clear Cache: Run

php yii cache/flush-all

Check .htaccess (For Apache)

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

Restart Web Server (For Nginx/Apache)


Conclusion

Yii2 routing system provides flexibility to define clean and SEO-friendly URLs. We covered:

  • Enabling Pretty URLs
  • Defining custom routes
  • Handling dynamic parameters
  • Generating links using Url::to()
  • Setting up routes for Yii2 Modules 
  • Generating URLs using 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