Yii2.0默认的访问形式为:php
http://www.xxx.com/index.php?r=post/index&id=100
通常咱们都会考虑将其美化一下,变成以下的形式:html
http://www.xxx.com/post/100.html
接下来就是美化的步骤nginx
在入口文件(index.php)所在的目录下新建一个文本文件,接着另存为.htaccess,用编辑器打开此文件加入:web
RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1]
保存便可数组
在nginx配置文件(我本地是/conf/vhosts/test.conf文件)中加入:浏览器
location/{ try_files $uri $uri/ /index.php?$query_string; }
整个server配置相似:服务器
server { listen80; server_name test.yii.com; root "/Projects/yii/web"; location / { index index.html index.htm index.php; try_files $uri $uri/ /index.php?$query_string; } error_page /50x.html; location = /50x.html { root html; } location~ \.php(.*)$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_split_path_info ^((?U).+\.php)(/?.*)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; include fastcgi_params; } }
打开config目录下的web.php,在$config = [ 'components'=>[] ]中加入如下内容:yii
'urlManager' => [ //开启url美化 'enablePrettyUrl' => true, //隐藏index.php 'showScriptName' => false, //禁用严格匹配模式 'enableStrictParsing' => false, //url后缀名称 'suffix'=>'.html', //url规则 'rules' => [ //post后面跟上数字的url,则将数字赋给id参数,而后传递给 post/view,实际上访问的是 post/view?id=XXX 'post/<id:\d+>'=>'post/view' ] ],
rules数组中配置具体的路由规则编辑器
至此,配置完毕。post
http服务器中配置的虚拟域名必须直接指向入口文件所在目录,不然在url省略index.php的状况下,http服务器没法正确访问到项目。
配置test.yii.com虚拟域名指向了/Projects/yii/web目录,而你的项目入口文件实际上是在/Projects/yii/web/test目录
浏览器访问项目的url是:
http://test.yii.com/test/index.php?r=post/view&id=100
这时你把url换成
http://test.yii.com/test/post/100.html
是行不通的