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` => false,
`rules` => [
],
],
如果配置檔案中已經有了該配置項,但是被註釋掉了。將其註釋去掉即可
此時,yii2.0已經支援以pathinfo的形式訪問了。不過路徑還是形如:my.oschina.net/index.php/post/index
我們接下來希望把index.php去掉
二、配置http伺服器
1、Apache
在入口檔案(index.php)所在的目錄下新建一個文字檔案,接著另存為.htaccess,用編輯器開啟此檔案加入:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
儲存即可
2、Nginx
在nginx配置檔案(我本地是/conf/vhosts/test.conf檔案)中加入:
location/{
try_files $uri $uri/ /index.php?$query_string;
}
整個server配置類似:
server {
listen 80;
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伺服器
至此,配置完畢。