The URLs linking various pages of our blog application currently look ugly. For example, the URL for the page showing a post looks like the following:
/index.php?r=post/show&id=1
In this section, we describe how to beautifying these URLs and make them SEO-friendly. Our goal is to be able to use the following URLs in the application:
/index.php/tag/yii
: leads to the page showing a list of posts with tag yii
;/index.php/posts
: leads to the page showing the latest posts;/index.php/post/1
: leads to the page showing the detail of the post with ID 1;/index.php/post/update/1
: leads to the page that allows updating the post with ID 1.To achieve our goal, we modify the application configuration as follows,
return array(
......
'components'=>array(
......
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'tag/<tag>'=>'post/list',
'posts'=>'post/list',
'post/<id:\d+>'=>'post/show',
'post/update/<id:\d+>'=>'post/update',
),
),
),
);
In the above, we configure the urlManager component by setting its urlFormat
property to be path
and adding a set of rules
.
The rules are used by urlManager
to parse and create the URLs in the desired format. For example, the first rule says that if a URL /index.php/tag/yii
is requested, the urlManager
component should be responsible to dispatch the request to the route post/list
and generate a tag
GET parameter with the value yii
. On the other hand, when creating a URL with the route post/list
and parameter tag
, the urlManager
component will also use this rule to generate the desired URL /index.php/tag/yii
. For this reason, we say that urlManager
is a two-way URL manager.
The urlManager
component can further beautify our URLs, such as hiding index.php
in the URLs, appending suffix like .html
to the URLs. We can obtain these features easily by configuring various properties of urlManager
in the application configuration. For more details, please refer to the Guide.
Signup or Login in order to comment.