yii2 路由重写

Yii配置

<?php
return [
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true, //启用URL美化
            'showScriptName' => false, //禁用 index.php
            'suffix' => '.html', //启用后缀
            'rules' => [
            ],
        ]
    ],
];
'rules' => [
      '<controller:\w+>/<action:\w+>/<pid:\d+>'=>'<controller>/<action>'
 ]
<controller:\w+> //这是指匹配控制器
<action:\w+> //这是指匹配控制器内的方法
<pid:\d+> //这里指获取相应的请求参数的key \Yii::$app-&gt;request->get('pid');

 Nginx配置

在配置文件增加

if (!-e $request_filename){  
rewrite ^/(.*) /index.php last;  
}

 Apache配置

Options +FollowSymLinks
IndexIgnore  */*
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php

将以上代码保存为.htaccess文件放在应用入口目录下。并且apache要开启rewrite模块