arrow_back
Back

Yii2 routing: route format, pretty URLs, and URL rules

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

In Yii2 a route has the following format:

[ModuleID/]ControllerID/ActionID

By default the route is passed through the r query parameter:

/index.php?r=post%2Fview&id=100

The application has a default route:

$config = [
    'defaultRoute' => 'main/index',
];

Pretty URLs

$config = [
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                // routing rules
            ],
        ],
    ],
];

You also need an .htaccess file with the rewrite rules:

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

Writing rules

Simple pattern to route mapping:

[
    'posts' => 'post/index',
]

Verbose form with a suffix:

[
    [
        'pattern' => 'posts',
        'route' => 'post/index',
        'suffix' => '.json',
    ],
]

Named parameter with a pattern:

[
    'post/<id:\d+>' => 'post/view',
]

Optional parameters with defaults:

[
    [
        'pattern' => 'posts/<page:\d+>/<tag>',
        'route' => 'post/index',
        'defaults' => ['page' => 1, 'tag' => ''],
    ],
]

Restricting rules by HTTP method:

[
    'PUT, POST post/<id:\d+>' => 'post/update',
    'DELETE post/<id:\d+>' => 'post/delete',
    'post/<id:\d+>' => 'post/view',
]

Maintenance mode

catchAll routes every request to a single action — handy for a “site is under maintenance” page:

$config = [
    'catchAll' => ['site/offline'],
];

Recommendation

Keep the routing configuration in a separate file.

Useful

Current controller and action:

Yii::$app->controller->id;
Yii::$app->controller->action->id;
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Yii2 controllers: actions, behaviors, filters, and responses

arrow_forward