yii2自带的urlManage可以很方便的提供url美化,但是其默认配置的却是Apache环境下的,对于nginx,还需要我们额外的修改nginx.conf配置。
yii2配置
直接上代码
‘components’ => [
'urlManager' => [
'enablePrettyUrl' => true,//开启URL美化
'showScriptName' => false,//禁用index.php文件
],
]
上述代码是在yii的配置文件中设置的,很简单的几行即可开启yii的url美化。
配置nginx
重点在这里
server {
listen 8081;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET';
root /usr/local/var/www/fangxin/frontend/web/;
index index.html index.htm index.php;
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=$1 last;
break;
}
}
location ~ \.php$ {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET';
add_header 'Access-Control-Allow-Methods' 'GET';
fastcgi_buffer_size 128k;
fastcgi_buffers 32 32k;
root /usr/local/var/www/fangxin/frontend/web/;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?r=$1 last;
break;
}
}
}
现在进行讲解:上述代码中,最重要的一段是在最后的rewrite这里,假设用户访问网址http://localhost:8081/fangxin/frontend/web/index.php?r=site/index,正常的情况下是跳转到我们的site控制器里的index这个方法,但是使用了urlManage美化之后,nginx读到的路由就会变成http://localhost:8081/fangxin/frontend/web/site/index,很显然,nginx会把site和index当成目录去找,找不到目录就报错。所以我们要告诉nginx,如果找不到site/index,那么你就跳转到index.php?r=site/index这里去,从而实现正常访问的目的。