yii2 nginx index.php,Yii2 高级模板通过配置 Nginx 一个 vhost 方便前后端访问

场景

每次使用 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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值