Yii - URL 规则
如果 yii\web\UrlRule,则 URL 规则是一个实例。启用漂亮的 URL 格式后,urlManager 组件将使用其 rules 属性中声明的 URL 规则。
要解析请求,URL 管理器将按声明的顺序获取规则并查找第一条规则。
步骤 1 − 修改 config/web.php 文件中的 urlManager 组件。
'urlManager' => [ 'showScriptName' => false, 'enablePrettyUrl' => true, 'rules' => [ 'about' => 'site/about', ] ],
步骤 2 − 转到您的 Web 浏览器,地址为 http://localhost:8080/about,您将看到关于页面。
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 浏览器的地址栏中输入地址 http://localhost:8080/site/contact.html,您将在屏幕上看到以下内容。请注意 html 后缀。