环境:lamp、Yii2高级模板
1、修改配置文件frontend/config/main.php
'urlManager' => [ //是否开启url美化 'enablePrettyUrl' => true, //是否显示index.php 'showScriptName' => false, //url后缀 //'suffix' => '.html', //url匹配规则,可以设置也可以不设置 'rules' => [ //数字post?id=12 --> /archives/12 '/archives/<id:\d+>' => 'post', //非纯数字xxx/xxxxx/index?id=w12 --> /xxx/xxxxx/w12 '/xxx/xxxxx/<id:[^.]*>' => 'xxx/xxxxx/index', ] ],
2、在网站web目录下创建.htaccess
[root@wrx web]# pwd /var/www/html/xxx/frontend/web [root@wrx web]# vim .htaccess #内容如下 RewriteEngine on # If a directory or a file exists, use the request directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Otherwise forward the request to index.php RewriteRule . index.php
3、Apache开启url重写
#修改httpd.conf LoadModule rewrite_module modules/mod_rewrite.so #如果未找到上面那一行,就添加;如果找到有注释,就将注释去掉。
注:Yii2部分的rules设置
'rules' => [ // 为路由指定一个别名简化网址 'reg' => 'user/register', // 加id参数,这里用到了一点点正则,\d+在正则中表示至少一位的纯数字 'article/<id:\d+>' => 'article/view', //标准的控制器/方法显示 '<controller:\w+>/<action:\w+>'=>'<controller>/<action>', //加id参数 '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>', // controller和action进行严格限制 '<controller:(post|comment)>/<id:\d+>/<action:(create|update|delete)>' => '<controller>/<action>', // 包含了 HTTP 方法限定,用于restful风格的Web Server 'DELETE <controller:\w+>/<id:\d+>' => '<controller>/delete', // 配置Web Server ,接收 *.wrx.com 域名的请求 'http://<user:\w+>.wrx.com/<lang:\w+>/profile' => 'user/profile', ]