SEO friendly URL in Yii

I need a rule for the http://example.com/post/view/id/1 url, which will be displayed as follows http://example.com/post/post_title . Instead of an identification number, I want to display the name or title of the message.

My config is as follows:

'urlManager'=>array( 'urlFormat'=>'path', 'rules'=>array( //'<controller:\w+>/<id:\d+>'=>'<controller>/view', //'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>', //'<controller:\w+>/<action:\w+>'=>'<controller>/<action>', ), 'showScriptName'=>false, ), 
+6
source share
3 answers

you need to have a rule like this

 'post/<post_title:\w+>'=>'postController/view/title/<post_title>', 

This simply tells the application to forward requests starting with post / post_title to the actionView, where $ _GET ['title'] is set to post_title ...

Hope this helps.

+3
source

This is a simple rule.

 'post/<post_title:\w+>' => 'post/view' 

If you need the URL http://example.com/post/some-title-with-hyphen

 'post/<post_title:[-\w]+>' => 'post/view' 

And you need a controller action with $ post_title argument

 public function actionView($post_title) { ... 
+2
source

by default, Yii only returns the message identifier, if you want to display the message header, you need to access the database yourself in the user rules of the Url class. yii tutorial has an example using-custom-url-rule-classes

+1
source

Source: https://habr.com/ru/post/902990/


All Articles