SEO friendly url in Yii
Asked Answered
U

3

6

I need a rule for http://example.com/post/view/id/1 url that will be displayed like this http://example.com/post/post_title. Instead of the id number i want to display the post name or title.

My config looks like this:

 '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,
    ),
Uranus answered 3/12, 2011 at 9:56 Comment(0)
R
3

you need to have a rule that looks like this

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

This just tells the app to forward requests that start with a post/post_title to the post controller's actionView where $_GET['title'] is set to post_title...

Hope that helps.

Rost answered 13/5, 2012 at 20:50 Comment(0)
B
3

It's simple rule

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

If need url like this 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) {
    ...
Berey answered 27/12, 2014 at 1:15 Comment(0)
V
1

in default, Yii only retreive the post id, if you want to display the post title, you need to access the DB your self in a custom Url class rules. there is an example in the yii tutorial called using-custom-url-rule-classes

Vernacularism answered 3/12, 2011 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.