Yii - URL 格式



當 Yii 應用程式處理請求的 URL 時,首先,它會將 URL 解析為一個路由。然後,為了處理請求,此路由用於例項化相應的控制器操作。此過程稱為 **路由**。反向過程稱為 URL 建立。**urlManager** 應用程式元件負責路由和 URL 建立。它提供兩種方法:

  • **parseRequest()** - 將請求解析為路由。

  • **createUrl()** - 根據給定的路由建立 URL。

URL 格式

**urlManager** 應用程式元件支援兩種 URL 格式:

  • 預設格式使用查詢引數 r 來表示路由。例如,URL ** /index.php?r=news/view&id=5 ** 表示路由 **news/view** 和 **id** 查詢引數 5。

  • 漂亮 URL 格式使用額外的路徑和入口指令碼名稱。例如,在前面的示例中,漂亮格式將為 ** /index.php/news/view/5 **。要使用此格式,您需要設定 URL 規則。

要啟用漂亮 URL 格式並隱藏入口指令碼名稱,請執行以下步驟:

**步驟 1** - 以以下方式修改 **config/web.php** 檔案。

<?php
   $params = require(__DIR__ . '/params.php');
   $config = [
      'id' => 'basic',
      'basePath' => dirname(__DIR__),
      'bootstrap' => ['log'],
      'components' => [
         'request' => [
            // !!! insert a secret key in the following (if it is empty) -
               //this is required by cookie validation
            'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',
         ],
         'cache' => [
            'class' => 'yii\caching\FileCache',
         ],
         'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
         ],
         'errorHandler' => [
            'errorAction' => 'site/error',
         ],
         'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
         ],
         'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
               [
                  'class' => 'yii\log\FileTarget',
                  'levels' => ['error', 'warning'],
               ],
            ],
         ],
         'urlManager' => [ 
            'showScriptName' => false, 
            'enablePrettyUrl' => true 
         ], 
         'db' => require(__DIR__ . '/db.php'), 
      ], 
      'modules' => [
         'hello' => [
            'class' => 'app\modules\hello\Hello',
         ],
      ],
      'params' => $params,
   ];
   if (YII_ENV_DEV) {
      // configuration adjustments for 'dev' environment
      $config['bootstrap'][] = 'debug';
      $config['modules']['debug'] = [
         'class' => 'yii\debug\Module',
      ];
      $config['bootstrap'][] = 'gii';
      $config['modules']['gii'] = [
         'class' => 'yii\gii\Module',
      ];
   }
   return $config;
?>

我們剛剛啟用了 **漂亮 URL 格式** 並停用了入口指令碼名稱。

**步驟 2** - 現在,如果您在 Web 瀏覽器的位址列中鍵入 **https://:8080/site/about**,您將看到漂亮 URL 正在執行。

Pretty URL

請注意,URL 不再是 **https://:8080/index.php?r=site/about**。

廣告

© . All rights reserved.