yii使用pathinfo路由
Yii2.0默认的访问形式为:my.oschina.net/index.php?r=post/index,一般我们都会配置成pathinfo的形式来访问,形如:my.oschina.net/post/index,这样更符合用户习惯。
一、配置yii
打开config目录下的web.php,在$config = [ ‘components’=>[] ]中加入以下内容:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => true,
'rules' => [
],
],
],
],
如果配置文件中已经有了该配置项,但是被注释掉了。将其注释去掉即可
此时,yii2.0已经支持以pathinfo的形式访问了。不过路径还是形如:my.oschina.net/index.php/post/index
我们接下来希望把index.php去掉
二、配置http服务器
1、Apache
在入口文件(index.php)所在的目录下新建一个文本文件,接着另存为.htaccess,用编辑器打开此文件加入:
RewriteEngine onRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule . index.php
保存即可
2、Nginx
在nginx配置文件(我本地是/conf/vhosts/test.conf文件)中加入:
location/{
try_files $uri $uri/ /index.php?$query_string;
}
try_files $uri $uri/ /index.php?$query_string;
}
整个server配置类似:
server { listen 80;
server_name test.yii.com;
location / { index index.html index.htm index.php;
try_files $uri $uri/ /index.php?$query_string;
}
location = /50x.html {
root html;
}
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;
}
}
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 500 502 503 504 /
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;
}
}
三、重启http服务器
至此,配置完毕。