Apache服务器的配置
修改httpd.conf配置文件
将LoadModule rewrite_module modules/mod_rewrite.so前面的注释#号去掉。
添加如下内容
<Directory "path/to/basic/web"> # use mod_rewrite for pretty URL support 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 # ...other settings... </Directory>
注意其中的path/to/basic/web修改成你的根目录,最后不要忘记重启apache服务器。
Nginx服务器的配置
修改nginx.conf配置文件,在域名对应的server{}内添加如下内容
location / { # Redirect everything that isn't a real file to index.php try_files $uri $uri/ /index.php$is_args$args; }
一、添加YII配置
配置文件:config/main.php
<?php return [ 'components' => [ 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ ], ] ], ];
相应的配置介绍
'showScriptName' => false, // 禁用 index.php 'enablePrettyUrl' => true, // 启用 URL美化 'suffix' => '.html', // 在这里我们不配置,如果启用后缀,那么你的每个请求都会默认有.html的后缀
这样一来,你就可以隐藏路径中的index.php了
三、配置 rules
关键部分来了,下面要配置相应的解析规则了
转换前 URL:http://www.xxx.com/product/view?pid=10
转换后 URL:http://www.xxx.com/product/view/10
那么就需要下面的配置
'rules' => [ '<controller:\w+>/<action:\w+>/<pid:\d+>'=>'<controller>/<action>' ] <controller:\w+> //这是指匹配控制器 <action:\w+> //这是指匹配控制器内的方法 <pid:\d+> //这里指获取相应的请求参数的key \Yii::$app->request->get('pid'); 如果希望添加后缀.html 'rules' => [ '<controller:\w+>/<action:view>/<pid:\d+>.html'=>'<controller>/<action>', ]
注意:
1.这样的配置会匹配所有的控制器
2.参数中的\d+代表匹配数字 如果你的想是字符串 那么请修改成\w+
如果想修改成匹配固定的控制器或者方法,请参考下面配置
'rules' => [ '<controller:product>/<action:view>/<pid:\d+>.html'=>'<controller>/<action>', ]
为了更好的将链接个性化配置,可以参照如下例子,在rules这个空的数组中添加相应的内容。
文章列表
/index.php?r=post/index
添加'post'=>'post/index'
通过id查看文章
/index.php?r=post/view&id=123
添加'post/<id:\d+>'=>'post/view'
其中\d+等价于[0-9]+
通过标题查看文章
/index.php?r=post/view&title=hello-world
添加'post/<title:\w+>'=>'post/view'
其中\w+等价于[A-Za-z0-9_]+
最后config/web.php可能如下所示
'components' => [ ... 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ 'post'=>'post/index', 'post/<id:\d+>'=>'post/view', ], ], ... ],