场景
每次使用 Yii2 高级模板都需要配置两个 vhost ,有没有觉得好烦?这篇文件就教你如何实现配置一个 vhost 实现前后台入口。
实战
先初始化项目入口文件以及其他
在项目根目录执行:
$ php init
修改 Nginx 配置
修改之后的最终参考代码,具体需要按照你项目情况改动:
server {
listen 80;
server_name yii2ad.dev.com;
root /home/www/yii2ad/;
location / {
root /home/www/yii2ad/frontend/web;
# nginx ignore index.php
try_files $uri /frontend/web/index.php?$args;
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
access_log off;
expires 360d;
try_files $uri =404;
}
}
location /admin {
alias /home/www/yii2ad/backend/web;
rewrite ^(/admin)/$ $1 permanent;
try_files $uri /backend/web/index.php?$args;
}
# avoiding processing of calls to non-existing static files by Yii
location ~ ^/admin/(.+\.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar))$ {
access_log off;
expires 360d;
rewrite ^/admin/(.+)$ /backend/web/$1 break;
rewrite ^/admin/(.+)/(.+)$ /backend/web/$1/$2 break;
try_files $uri =404;
}
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;
}
}
修改配置文件
修改 frontend/config/main.php 文件:
return [
'components' => [
// something code
'request' => [
'csrfParam' => '_csrf-frontend',
'baseUrl' => '', // 修改 baseUrl
],
// 可选操作,打开路由美化
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [],
],
],
// something code
];
修改 backend/config/main.php 文件:
return [
'components' => [
// something code
'request' => [
'csrfParam' => '_csrf-backend',
'baseUrl' => '/admin', // 修改 baseUrl
],
// 可选操作,打开路由美化
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [],
],
],
// something code
];
总结
按照以上操作之后,你就可以:
通过 http://yii2ad.dev.com/ 来实现前台的访问,实际入口文件为 frontend/web/index.php
通过 http://yii2ad.dev.com/admin/ 来实现后台的访问,实际入口文件为 backend/web/index.php
最后友情提醒一下:这样操作之后前台就不能配置名为 admin 的模块了。
使用 Nginx 来实现这种效果,带来的好处并不明显。有些人用的是虚拟主机,不能配置服务器,只有 Apache,这样的话要想使用 Yii2 就很不方便,其实我们可以在项目根目录下添加一个 .htaccess 文件就可以同样实现这个效果。
# prevent directory listings
Options -Indexes
# follow symbolic links
Options FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/admin/$
RewriteRule ^(admin)/$ /$1 [R=301,L]
RewriteCond %{REQUEST_URI} ^/admin
RewriteRule ^admin(/.+)?$ /backend/web/$1 [L,PT]
RewriteCond %{REQUEST_URI} ^.*$
RewriteRule ^(.*)$ /frontend/web/$1
此方法来源于开源项目YEE CMS。