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;
Andrew Dorokhov