Categories

Introduction

YII URL router is quite powerful and does two main tasks: it resolves URLs into internal routes and creates URLs from these routes. Let’s try to understand how to configure application rules by simple example.

Let’s begin

As a first step: Create a fresh Yii application and find your protected/config/main.php. It should contain the following:

Let’s configure our application server to use clean URLs. If you are using Apache with mod_rewrite and AllowOverride turned on, then add the following lines into your .htaccess file under the root folder:

What is happening!

Let’s review what we did and how it works. Have a look at the first rule:'home' => 'site/index',

What is site/index exactly?

In the Yii framework, a format for an internal route is moduleID/controllerID/actionID. For example, the actionPage method of SiteController corresponds to the site/page route. So, the controller ID should be its name without the Controller postfix and make its first letter lowercased. To get an action ID, you should take action method name without the action prefix and, again, make its first letter lowercased.

Now, what is home?

To have a better understanding, we need to know, at least perfunctorily, what’s happening when we access our application using different URLs.

When we are using /home, URL router checks our rules one by one starting from the top trying to match URL entered with the rule. If the match is found, then the router is getting controller and its action from an internal route assigned to the rule and is executing it. So, /home is the URL pattern that defines which URLs will be processed by the rule it belongs to.

More Rules…

You can create parameterized rules using a special syntax. Let’s take the third one:'page/<alias>' => 'site/page',
Here, we are defining an alias parameter that should be specified in URL after /page/. It can be virtually anything and it will be passed as $alias parameter to
SiteController::actionPage($alias).

You can define a pattern for such a parameter:'<alias:about>' => 'site/page',
Alias here should match about or else, the rule will not be applied.

Read More

Visit the following URLs to get more information and examples related to this topic.