YII2实现隐含backend\web和frontend\web及前后台分别登录验证

由于很多虚拟主机没有提供修改主页根目录的功能, 导致我们无法将域名绑定到frontend\web目录下, 只能用 www.xxx.com/frontend/web来访问我们的网站和 www.xxx.com/backend/web来访问后台, 这样很不方便和美观, 所以我们要做的是把backend/web和frontend/web隐含,直接用 www.xxx.com来访问我们的网站.

一. 在网站的根目录下面创建.htaccess文件

Options -Indexes
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} ^/(assets|css)
RewriteRule ^assets/(.*)$ frontend/web/assets/$1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/$1 [L]
RewriteRule ^js/(.*)$ frontend/web/js/$1 [L]
RewriteRule ^images/(.*)$ frontend/web/images/$1 [L]
RewriteRule ^plugins/(.*)$ frontend/web/plugins/$1 [L]
RewriteCond %{REQUEST_URI} !^/(frontend|backend)/web/(assets|css)/
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ frontend/web/index.php

 

 

二. 修改前后台的config\main.php (注意红色部分的不同)

  前台:

return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'homeUrl' => '/',
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
'baseUrl' => '',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
........(下面略)

 后台:

return [
    'id' => 'app-backend',
    'basePath' => dirname(__DIR__),
'homeUrl' => '/admin', 'controllerNamespace' => 'backend\controllers', 'bootstrap' => ['log'], 'modules' => [], 'components' => [ 'request' => [ 'csrfParam' => '_csrf-backend', 'baseUrl' => '/admin', ], 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => true, 'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true], } ], 'session' => [ // this is the name of the session cookie used for login on the backend 'name' => 'advanced-backend', ],
........(下面略)

 

 五. 修改common\config\main.php 开启url美化

'components' => [
    ....

        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules'=>[
            ],
        ],

      ....
]

 

六.在frontend\web和backend\web目录下分别创建.htaccess文件

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]

 

至此我们即可用 www.xxx.com和 www.xxx.com/admin 来访问我们的前后台, 而不用输入frontend\web 和 backend\web , 并且前后台的登录验证是分开的, 就前台登录后, 如果访问后台, 同样也要登录, 后台退出也不造成前台退出.

 

posted on 2017-06-19 14:04  WonderBlog  阅读(447)  评论(0编辑  收藏  举报