I have a Yii 2 application and I'd like to use some pretty URL. In my config file I already enable the pretty URL with the below rules:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
//'suffix' => '.html',
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>/<slug:[a-zA-Z0-9_-]+>/' => '<controller>/<action>/<slug>',
'<controller:[\w\-]+>/<action:[\w\-]+>/slug/<slug:\d+>/id/<id:\w+>/itmNo/<itmNo:\w+>' => '<controller>/<action>/<slug>',
],
],
And the URL result is something like this http://192.168.1.101/myproject/item?Id=mens-body-fitted-t-shirt-2018-summer-fashion-2&itmNo=82813720
In the above URL item
is the controller while Id
and itmNO
are queries, I'd like to get something like this below URL http://192.168.1.101/myproject/item/mens-body-fitted-t-shirt-2018-summer-fashion-2/82813720
The query name are replaced with /
. How can I do this in Yii2 and still get the query in my controller to make the normal search?
My url creation looks like this
$myurl = \Yii::$app->UrlManager->createUrl(['/item','Id'=>$items['slug'].'-'.$items['product_id'],'itmNo'=>$items['item_number']]);
You need to put the most precise rule at the beginning:
'rules' => [
'<controller:[\w\-]+>/<action:[\w\-]+>/slug/<slug:\d+>/id/<id:\w+>/itmNo/<itmNo:\w+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>/<slug:[a-zA-Z0-9_-]+>/' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'<controller:\w+>/<id:\d+>' => '<controller>/view',
],
And create URL like this:
$myurl = \Yii::$app->UrlManager->createUrl([
'/item/view',
'id' => $items['product_id'],
'slug' => $items['slug'],
'itmNo' => $items['item_number'],
]);
I think, what you are looking for is this rule:
> '<controller:[\w\-]+>/<action:[\w\-]+>/<id:[\w\-]+>/<itmNo:\w+>'=>'<controller>/<action>'
In this case, you should indicate a controller name, id and itmNo as parameters. Don't forget to put this rule before more general ones. Sample query:
\Yii::$app->UrlManager->createUrl(['item/view','id'=>'slug'.'-'.'2', 'itmNo'=>'12313'])
read this post for better understanding