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

本文详细介绍如何在Yii2框架中配置多模块应用,并实现美观的URL重写,包括前端和后台模块的独立配置及访问路径调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

namespacecommon\components;
classRequest extends\yii\web\Request {
  public$web;
  public$adminUrl;
  publicfunction getBaseUrl(){
    returnstr_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.
  */
  publicfunction resolvePathInfo(){
    if($this->getUrl() === $this->adminUrl){
      return"";
    }else{
      returnparent::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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值