Yii Tutorial on Yii Rules of URL

a url rule is an instance if yii\web\urlrule. the urlmanager components uses the url rules declared in its rules property when the pretty url format is enabled.

to parse a request, the url manager obtains the rules in the order they are declared and looks for the first rule.

step 1 − modify the urlmanager component in the config/web.php file.

'urlmanager' => [
   'showscriptname' => false,
   'enableprettyurl' => true,
   'rules' => [
      'about' => 'site/about',
   ]
],

step 2 − go to your web browser at http://localhost:8080/about, you will see the about page.

modified urlmanager component

a url rule can be associated with query parameters in this pattern −

<paramname:regexp>, where −

  • paramname − the parameter name

  • regexp − an optional regular expression used to match parameter values

suppose, we have declared the following url rules −

[
   'articles/<year:\d{4}>/<category>' => 'article/index',
   'articles' => 'article/index',
   'article/<id:\d+>' => 'article/view',
]

when the rules are used for parsing

  • /index.php/articles is parsed into the article/index
  • /index.php/articles/2014/php is parsed into the article/index
  • /index.php/article/100 is parsed into the article/view
  • /index.php/articles/php is parsed into articles/php

when the rules are used for creating urls

  • url::to(['article/index']) creates /index.php/articles

  • url::to(['article/index', 'year' => 2014, 'category' => 'php']) creates /index.php/articles/2014/php

  • url::to(['article/view', 'id' => 100]) creates /index.php/article/100

  • url::to(['article/view', 'id' => 100, 'source' => 'ad']) creates /index.php/article/100?source=ad

  • url::to(['article/index', 'category' => 'php']) creates /index.php/article/index?category=php

to add a suffix to the url, you should configure the yii\web\urlmanager::$suffix property.

step 3 − modify the urlcomponent in the config/web.php file.

'urlmanager' => [
   'showscriptname' => false,
   'enableprettyurl' => true,
   'enablestrictparsing' => true,
   'suffix' => '.html'
],

step 4 − type the address http://localhost:8080/site/contact.html in the address bar of the web browser and you will see the following on your screen. notice the html suffix.

notice html suffix