一、什么是路由重写
原本的HTTP访问地址: www.test.com/index.php?r=post/view&id=100 表示这个请求将由PostController 的 actionView来处理。
重写后的HTTP访问地址 www.test.com/post/view/id/100 这样的链接看起来简洁美观,对于用户比较友好。同时,也比较适合搜索引擎的胃口, 据说是SEO的手段之一。
二、Apache 路由重写
(一)开启Apache的重写模块
1. 打开apache的config的 hhttpd.conf 将 #LoadModule rewrite_module modules/mod_rewrite.so 的#号去掉
2. 重启Apache服务器即可
(二)虚拟主机配置
1. 打开 Apache\conf\vhosts.conf配置路径
2. 将配置修改为如下:
<VirtualHost 127.0.0.1:>
ServerName test-yii2.com
DocumentRoot F:/wamp64/www/yii2/frontend/web
<Directory "F:/wamp64/www/yii2/frontend/web">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
RewriteEngine on
# 如果请求的是真实存在的文件或目录,直接访问
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 如果请求的不是真实文件或目录,分发请求至 index.php
RewriteRule . index.php
</Directory>
</VirtualHost>
3. 重启Apache
(三)还有另外一种配置方式,无需重启Apache服务器,当时改当时生效。
1. 在 “F:/wamp64/www/yii2/frontend/web” 目录下增加 .htaccess 代码如下:
RewriteEngine on
# 如果请求的是真实存在的文件或目录,直接访问
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 如果请求的不是真实文件或目录,分发请求至 index.php
RewriteRule . index.php
(四) YII配置
1. 在main.php下 components
这个数组中增加如下如下配置:
'urlManager' => [
'enablePrettyUrl' => true, //开启美化url配置,默认关闭
'enableStrictParsing' => false, //不启用严格解析,默认不启用.如果设置为true,则必须建立rules规则,且路径必须符合一条以上规则才允许访问
'showScriptName' => false, //隐藏index.php
'rules' => [
// http://frontend.com/site/index 重写为 http://frontend.com/site
'<controller:\w+>/'=>'<controller>/index',
// http://frontend.com/site/view?id=1 重写为 http://frontend.com/site/1
'<controller:\w+>/<id:\d+>' => '<controller>/view',
// http://frontend.com/site/ceshi?id=123 重写为 http://frontend.com/site/ceshi/123
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
]
],