Friday, June 08, 2012

YII: How to make Clean SEO-friendly URLs


* Create Slug field in your database table
If you prefer not to create slug every time someone goes to the homepage or the main news page, you can create slug field in your database table.  It is a lot easier to keep track and you can modify the slug later as well. 

* Use SlugBehaviors - http://www.yiiframework.com/extension/slug-behavior/
Installation was almost too easy.  You download and extract the release file under models/behaviors 
And in the model, add the following: (e.g. /protected/model/post.php)

public function behaviors(){
    return array(
        'SlugBehavior' => array(
            'class' => 'application.models.behaviors.SlugBehavior',
            'slug_col' => 'slug',
            'title_col' => 'title',
            'max_slug_chars' => 125,
            'overwrite' => false
        )
    );
}

That's it! 

* Modify config/main.php
The tricky part was how to modify the UrlManager in /protected/config/main.php as below: 

 'urlManager' => array(
….
                'post/<id:\d+>/<slug>/*' => 'post/view',
                'post/<id:\d+>/*' => 'post/view',
), 

Make sure the order is correct or else they wouldn't work because the first rule is applied first. 

* Use Chtml::link to create links
Then, you can use Chtml::link in the following way
 echo CHtml::link(CHtml::decode($data->title), array('/post/view/', 'id'=>$data->id, 'slug'=>$data->slug));
                
Here are some articles that was helpful!

3 comments:

Unknown said...

Hello how i manage seo with cms

Peter Bach said...

This was a really great contest and hopefully I can attend the next one. It was alot of fun and I really enjoyed myself.. seo for small business website

Adell Dolly said...

Thank you for the update, very nice site.. marketing1on1.com/buy-backlinks