[
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'suffix' => '.html',
'rules' => [
// ...
],
],
],
]
### 示例1 url 正则匹配
'rules' => [
posts/4}>/' => 'post/index',
'posts' => 'post/index',
'post/' => 'post/view',
],
### 示例2 url controller action正则匹配(常用)
'rules' => [
' / / ' => ' / ',
' / ' => ' /view',
' ' => ' /index',
],
### 示例3 url 默认参数
### 减少编写规则(允许数组参数)
'rules' => [
'' => '/index' ,
[
'pattern' => 'posts//' ,
'route' => 'post/index',
'defaults' => ['page' => 1, 'tag' => ''],
],
],
### 示例4 域名匹配
'rules' => [
'http://.example.com/posts' => 'post/index',
'http://admin.example.com/login' => 'admin/user/login',
'http://www.example.com/login' => 'site/login',
],
### 示例5 请求方式匹配
'rules' => [
'PUT,POST post/' => 'post/create',
'DELETE post/' => 'post/delete',
'post/' => 'post/view',
],
### 动态加载路由设置 bootstrap (module模块使用更多)
public function bootstrap($app)
{
$app->getUrlManager()->addRules([
// rule declarations here
], false);
}
### 自定义路由类
#配置
'rules' => [
'' => '/index' ,
[
'class' => 'app\components\CarUrlRule',
],
],
#php实现
namespace app\components;
use yii\web\UrlRuleInterface;
use yii\base\Object;
class CarUrlRule extends Object implements UrlRuleInterface
{
public function createUrl($manager, $route, $params)
{
if ($route === 'car/index') {
if (isset($params['manufacturer'], $params['model'])) {
return $params['manufacturer'] . '/' . $params['model'];
} elseif (isset($params['manufacturer'])) {
return $params['manufacturer'];
}
}
return false; // this rule does not apply
}
public function parseRequest($manager, $request)
{
$pathInfo = $request->getPathInfo();
if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) {
// check $matches[1] and $matches[3] to see
// if they match a manufacturer and a model in the database
// If so, set $params['manufacturer'] and/or $params['model']
// and return ['car/index', $params]
}
return false; // this rule does not apply
}
}
异常处理方法:
##参数配置
'errorHandler' => [
'errorAction' => 'site/error',
],
引用BKDUCK博客 http://www.bkduck.com/article/20