One of the "hidden" features of Yii URL router is that you can use regular expressions that are pretty powerful when it comes to strings handling.
Getting ready
Create a fresh Yii application using yiic webapp as described in the official 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>',
),
),
Delete everything from rules as we are going to start from scratch.
In your protected/controllers, create PostController.php with the following code inside:
class PostController extends CController
{
public function actionView($alias)
{
echo "Showing post with alias $alias.";
}
public function actionIndex($order = 'DESC')
{
echo "Showing posts ordered $order.";
}
public function actionHello($name)
{
echo "Hello, $name!";
}
}
This is our application controller we are going to access using our custom URLs.
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...
We want our PostController actions to accept parameters according to some rules and give "404 not found" HTTP response for all parameters that do not match. In addition, post index should have an alias URL archive.