当一个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格式(PrettyUrl)使用入口脚本加上名额外的路径。例如,在前面的例子,漂亮的格式将是
/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' => 'xuhuhu.com', ], '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' => [ 'admin' => [ 'class' => 'app\modules\admin\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格式(PrettyUrl),并禁用了入口脚本名称。
请注意,URL不再是 http://localhost:8080/index.php?r=site/about.