Yii2 UrlManager Rule For String

473 views Asked by At

I'm trying to create a simple rule url, and I can't get it to work.

I want the following rule:

mysite.com/[username]

to go to

mysite.com/kit/page?id=[username]

Is this possible?. Right now I only have one rule, but I need to keep that one as well

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
    '' => 'site/index',
    ],
],
1

There are 1 answers

0
Muhammad Omer Aslam On

If I understand correctly you are saying that you have an existing page mysite.com/kit/page?id=[username] which should be shown if you type in the URL mysite.com/[username] in the address bar, if yes then you can update the urlManager like below

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '/' => 'site/index',
        '<id:\w+>' => 'kit/page'
    ]
]

Ideally, I would use mysite.com/kit/[username] to avoid conflicts with any other controller which somehow matches up with any username and use 'kit/<id:\w+>' => 'kit/page'.

Note : \w+ matches any word character (equal to [a-zA-Z0-9_]), so if your username can have any other character allowed you might have to update the pattern, for example to allow - you should change the rule to '<id:[\w\-]+>' => 'kit/page'