Tuesday, July 3, 2012

Configuring URL rules in YII

Yii URL router is quite powerful and does two main tasks: it resolves URLs into internal routes
and creates URLs from these routes. Router rules description is scattered over the official Yii
guide and API docs. Let's try to understand how to configure application rules by example.
Getting ready
1. Create a fresh Yii application using yiic webapp as described in the official guide
(http://www.yiiframework.com/doc/guide/) and find your protected/
config/main.php. It should contain the following:
// application components
'components'=>array(

// uncomment the following to enable URLs in path-format
/*
'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>',
),
),
2. Delete everything from rules as we are going to start from scratch.
3. In your protected/controllers, create WebsiteController.php with the
following code inside:
class WebsiteController extends CController
{
public function actionIndex()
{
echo "index";
}
public function actionPage($alias)
{
echo "Page is $alias.";
}
}
This is the application controller we are going to customize URLs for.
4. Configure your application server to use clean URLs. If you are using Apache with
mod_rewrite and AllowOverride turned on, then you should add the following
lines to the .htaccess file under your webroot folder:
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
How to do it...
Our website should display the index page at /home and all other pages at /page/<alias_
here>. Additionally, /about should lead to a page with alias about.
1. Add the following to your rules in protected/config/main.php:
'home' => 'website/index',
'<alias:about>' => 'website/page',
'page/<alias>' => 'website/page',
2. After saving your changes, you should be able to browse the following URLs:
‰‰ /home
‰‰ /about
‰‰ /page/about
‰‰ /page/test

No comments:

Post a Comment