Reputation: 1831
I have the following URLs:
http://test.local/index.php?r=site%2Findex&slug=blog-detail
http://test.local/index.php?r=site%2Findex&slug=blog
http://test.local/
I want to get:
http://test.local/blog
http://test.local/blog-detail
http://test.local/
I am sending all requests to SiteController::actionIndex($slug)
, I am using Basic Application Template.
So far, I have been able to hide index.php
and site/index
.
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<slug\w+>' => 'site/index',
],
]
But it seems \w+
does not match strings with -
. Also if slug is empty it should show: http://test.local/
.
Upvotes: 0
Views: 397
Reputation: 22174
\w
does not match -
. You need to use [\w\-]
instead. And +
requires at least one char in your case. You should use *
instead:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<slug:[\w\-]*>' => 'site/index',
],
]
Upvotes: 2
Reputation: 81
What you are trying to make is make specific url based on GET param. With the following example if the user enters url test.local/Some-nice-article then the SiteController::actionIndex($slug)
function will get the param.
'urlManager' => [
'pattern' => '<slug>',
'route' =>'site/index',
'ecnodeParams' => false,
//class => any\custom\UrlRuleClass,
//defaults => []
]
Or you want another url to specify whether it is detailed view? You can do it this way:
'urlManager' => [
'pattern' => '<slug>-detail',
'route' =>'site/detail',
'ecnodeParams' => false,
//class => any\custom\UrlRuleClass,
//defaults => []
]
In this example, if the users puts the string '-detail' at the of the slug, then it will parse the route SiteController::actionDetail($slug)
to the request.
Please note that if you did not yet, enable prettyUrls in the config file
You can find a little more about this topic in this answer or in the Yii2 definitive guide
Upvotes: 1