Reputation: 11
How can I rewrite urls in Yii2. I want to rewrite url
/post/index?id=1
to
/post/1-example
Upvotes: 1
Views: 3406
Reputation: 31
You need to add below code to your backend/config/main.php
under components section:
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',),
],
I'd posted just because ians should be generic for all entire project.
Upvotes: 0
Reputation: 377
[
'components' => [
'urlManager' => [
'showScriptName' => false,
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'rules' => [
'post/<id:\d+>-<title:\w+>' => 'post/index',
],
],
],
]
Upvotes: 0
Reputation: 3818
You need to add following rules
code for urlManager
in config/main.php
(if advance template) or web.php
.
[
'components' => [
'urlManager' => [
'showScriptName' => false,
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'rules' => [
'post/<id:\d+>-example' => 'post/index',
],
],
],
]
Upvotes: 1