30.05.2013

Thema

How To use Friendly-Urls in Yii-Framework

How many times have I already read the question: How to create SEO friendly URLs in Yii. I show you a way how you can create it without any additional extensions. 

Provides please ensure that your web server has the mod_rewrite module enabled.

Steps:

  1. configure the .htaccess
  2. managed your app config
  3. write some rules
  4. modify your Model

To the index.php we need to get from the url to insert a few lines in our ".htaccess" file which can be found as standard in Yii framework in the www folder

1. the .htaccess

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    # Options +SymLinksIfOwnerMatch
    RewriteEngine On
    # RewriteBase /
    # If you are in a sub folder of your web root you
    # might have to enable something like this:
    #
    # RewriteBase /~pascal-brewing/app/frontend/www

    # Yii rewrite
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule . index.php
</IfModule>

Next we must configure Yii framework. The configuration file is by default in your / protected / config / main.php

2.Configure the UrlManager in YIi

    <?php
        'components' => array(
            'urlManager' => array(
                'urlFormat' => 'path',
                'showScriptName' => false,
                'rules' => array(
                    // default rules
                    '<controller:\w+>/<id:\d+>' => '<controller>/view',
                    '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                    '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
                ),
            ),
        )
    ?>

3. add some rules to your urlManager

    <?php
        'components' => array(
            'urlManager' => array(
                'urlFormat' => 'path',
                'showScriptName' => false,
                'rules' => array(
                    'blog/category/<slug>' => 'blog/category',
                    'blog/author/<slug>' => 'blog/author',
                    'blog/<slug>' => 'blog/post',
                    '<controller:\w+>/<id:\d+>' => '<controller>/view',
                    '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                    '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
                ),
            ),
        )
    ?>

4. Modified your Model

You have this rule

    'blog/' => 'blog/post',

Now you need this in your Model

    <?php
    /**
     * @return string the URL that shows the detail of the post
     */
    public function getUrl()
    {
        return Yii::app()----->createAbsoluteUrl('blog/post', array(
            'slug'=>$this->slug
        ));
    }
    ?>

the slug is a var in my Model. Here a complete example of Post Model, BlogController

 

Leave a Comment