Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Routing and pretty URLs

A route in Yii is a string like post/view: a controller and an action. By default it is passed in the r parameter, and URLs look like index.php?r=post/view&id=5. The urlManager component turns them into the familiar /posts/5.

Enabling pretty URLs

Open config/web.php. The urlManager block is already in the components section but commented out. Uncomment it:

// config/web.php
'components' => [
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
        ],
    ],
],

enablePrettyUrl enables URLs without the r parameter, showScriptName removes index.php from them. The list of posts now opens at http://localhost:8080/post/index, and a post at /post/view?id=5.

Rules

A rule links a URL pattern to a route. Rules go into the rules array: the pattern on the left, the route on the right.

'rules' => [
    'posts' => 'post/index',
    'posts/<id:\d+>' => 'post/view',
],

The list now opens at /posts, and a post at /posts/5. The <id:\d+> part is a named parameter: id is the name, and after the colon comes the regular expression "one or more digits". The value goes into the $id argument of the action. The URL /posts/abc does not match the rule and returns 404.

A rule for a request method

An HTTP method can be put before the pattern:

'rules' => [
    'POST posts' => 'post/create',
    'posts' => 'post/index',
],

A POST /posts request goes to the create action, and GET /posts to index.

URLs are not written in code as strings; they are built from a route with the Url helper:

use yii\helpers\Url;
 
Url::to(['post/index']);             // /posts
Url::to(['post/view', 'id' => 5]);   // /posts/5
Url::to(['post/view', 'id' => 5], true); // http://localhost:8080/posts/5
Url::home();                         // /

The first array element is the route, the rest are parameters. Yii picks a matching rule and assembles the URL. If the pattern in the rules changes, every link on the site updates by itself.

Web server setup

The built-in server php yii serve sends all requests to index.php on its own. For Apache this is done by the file web/.htaccess, created by hand:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

Requests for existing files (styles, images) are served as they are, the rest are passed to index.php.

Common mistake

Rules are checked from top to bottom, and the first match wins. If the general rule 'posts/<slug>' => 'post/slug' stands above 'posts/create' => 'post/create', the URL /posts/create goes to the first one. Put specific URLs above rules with parameters.

Thanks for reading!

Donate to the site — we work hard for you.