Yii - URL 規則



URL 規則是 yii\web\UrlRule 的一個例項。當啟用漂亮 URL 格式時,urlManager 元件使用在其 rules 屬性中宣告的 URL 規則。

為了解析請求,URL 管理器按照宣告的順序獲取規則,並查詢第一個規則。

步驟 1 − 修改 config/web.php 檔案中的 urlManager 元件。

'urlManager' => [
   'showScriptName' => false,
   'enablePrettyUrl' => true,
   'rules' => [
      'about' => 'site/about',
   ]
],

步驟 2 − 在您的 Web 瀏覽器中訪問 https://:8080/about,您將看到關於頁面。

Modified urlManager Component

URL 規則可以與此模式關聯查詢引數 −

<ParamName:RegExp>,其中 −

  • ParamName − 引數名稱

  • RegExp − 用於匹配引數值的可選正則表示式

假設,我們聲明瞭以下 URL 規則 −

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

當規則用於解析時 −

  • /index.php/articles 被解析為 article/index
  • /index.php/articles/2014/php 被解析為 article/index
  • /index.php/article/100 被解析為 article/view
  • /index.php/articles/php 被解析為 articles/php

當規則用於建立 URL 時 −

  • Url::to(['article/index']) 建立 /index.php/articles

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

  • Url::to(['article/view', 'id' => 100]) 建立 /index.php/article/100

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

  • Url::to(['article/index', 'category' => 'php']) 建立 /index.php/article/index?category=php

要向 URL 新增字尾,您應該配置 yii\web\UrlManager::$suffix 屬性。

步驟 3 − 修改 config/web.php 檔案中的 urlComponent

'urlManager' => [
   'showScriptName' => false,
   'enablePrettyUrl' => true,
   'enableStrictParsing' => true,
   'suffix' => '.html'
],

步驟 4 − 在 Web 瀏覽器的位址列中輸入地址 https://:8080/site/contact.html,您將在螢幕上看到以下內容。注意 html 字尾。

Notice HTML Suffix
廣告

© . All rights reserved.