How to change change / to - in yii2 url for specific action

720 Views Asked by At

I'm rewriting wordpress site to yii2. and I have to keep previous posts urls for some reasons! They are somethings like that

https://example.com/blog-thenameofpost

So I created a Blog controller and I have this link in this way

https://example.com/blog/view?id=thenameofpost

I don't know how can I write a urlManager rule for doing that. I just add this rules

    '<controller:\w+>/<id:\d+>' => '<controller>/view',
    '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
    '<controller:\w+>/<action:\w+>' => '<controller>/<action>',

and now this link https://example.com/blog/view?id=thenameofpost opens with something like it:
https://example.com/blog/thenameofpost

Are there any rules to open link with some thing like it https://example.com/blog/thenameofpost ?

1

There are 1 best solutions below

1
Jap Mul On

If you want to create a rule for https://example.com/blog-thenameofpost you could add the following rule.

'blog-<id>' => 'blog/view',

The left part is what you will actually see in your address bar. You can use < > to indicate a parameter. So this rule will match anything that starts with blog- and then consider the part after that as the id param. The right part is where this request should be routed to. So this request will end up in the BlogController and call actionView($id), where $id will be set to the <id> part; thenameofpost in the case of the example URL.

The rule for https://example.com/blog/thenameofpost would be

'blog/<id>' => 'blog/view'

Additional info: In the param part (left side) you can add additional info for matching the param. So <id:\d+> will only match digits, because of de \d+ part. For more info read the docs: http://www.yiiframework.com/doc-2.0/yii-web-urlmanager.html#$rules-detail