yii2 中关于隐藏frontend/web和backend/web的方法

测试环境直接通过虚拟环境配置即可,网上很多类似资源

不通过虚拟环境配置进行隐藏

1 进行根目录设置,给其配置根.htacess

Options +FollowSymlinks
RewriteEngine On
# deal with admin first
RewriteCond %{REQUEST_URI} ^/(admin) <------
RewriteRule ^admin/assets/(.*)$ backend/web/assets/ $1 [L]
RewriteRule ^admin/css/(.*)$ backend/web/css/ $1 [L]
RewriteCond %{REQUEST_URI} !^/backend/web/(assets|css)/ <------
RewriteCond %{REQUEST_URI} ^/(admin) <------
RewriteRule ^.*$ backend/web/index.php [L]
RewriteCond %{REQUEST_URI} ^/(assets|css) <------
RewriteRule ^assets/(.*)$ frontend/web/assets/ $1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/ $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
注意,如果访问的网站是存在目录的比如localhost/bb/backend/web 这样的需要对^/替换成^/bb/

2 创建相应的变量作为访问目录 common/ components/Request.php

namespace common\components;
class Request extends \yii\web\Request {
   public $web ;
   public $adminUrl ;
   public function getBaseUrl(){
     return str_replace ( $this ->web, "" , parent::getBaseUrl()) . $this ->adminUrl;
   }
   /*
     If you don't have this function, the admin site will 404 if you leave off
     the trailing slash.
     E.g.:
     Wouldn't work:
     site.com/admin
     Would work:
     site.com/admin/
     Using this function, both will work.
   */
   public function resolvePathInfo(){
     if ( $this ->getUrl() === $this ->adminUrl){
       return "" ;
     } else {
       return parent::resolvePathInfo();
     }
   }
}

3 在相应模块frontend/config/main.php and backend/config/main.php文件中添加下列配置

//frontend, under components array
'request' =>[
   'class' => 'common\components\Request' ,
   'web' => '/frontend/web'
],
'urlManager' => [
     'enablePrettyUrl' => true,
     'showScriptName' => false,
],
// backend, under components array
'request' =>[
   'class' => 'common\components\Request' ,
   'web' => '/backend/web' ,
   'adminUrl' => '/admin'
],
'urlManager' => [
     'enablePrettyUrl' => true,
     'showScriptName' => false,
],
4在相应模块的.htacess 中加入以下代码

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

www.project.com/admin, www.project.com

本地服务器

localhost/project_name/admin, localhost/project_name




你可能感兴趣的:(后台)