【问题标题】:yii2 urlManager + .htaccess = subdomain how to?yii2 urlManager + .htaccess = 子域怎么做?
【发布时间】:2016-08-05 06:08:45
【问题描述】:

这是挑战:我需要模仿子域。实际上,项目中的所有“子域”都是主 SiteController 的简单操作,例如

example.com/index.php/site/subsite?id=subname

example.com/index.php/site/about?id=subname

example.com/index.php/site/contacts?id=subname

等等。我需要它们看起来像

subname.example.com/

subname.example.com/about

subname.example.com/contacts

等等。我已经包含了这样的 urlManager 规则:

'rules' => [ 'http://<id:\w+>.site.com/about' => 'site/about', 'http://<id:\w+>.site.com/contacts' => 'site/contacts', 'http://<id:\w+>.site.com' => 'site/subsite', ],

并制作了一个 .htaccess 文件:

RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9]*).site.com [NC] RewriteRule %{HTTP_HOST} "^([a-zA-Z0-9]*)$.site.com" "site.com/index.php/subsite?id=$1" [L] 但它(可以预见)不起作用,因为我不擅长重写规则。我做错了什么?

【问题讨论】:

  • 为什么不使用 yii2-advance-app 并让每个应用服务一个域??

标签: .htaccess mod-rewrite yii2 subdomain yii-url-manager


【解决方案1】:

我会这样做:

  1. 在 Web 服务器上配置一个虚拟主机来托管所有子域并指向 Yii2 应用程序

  2. 编写组件Subdomain.php并放入frontend\components

<?php

namespace frontend\components;

use Yii;
use yii\base\Component;

class Subdomain extends Component {
    private $_subdomain = false;

    public function init() {
        parent::init();

        list($this->_subdomain) = explode('.', $_SERVER['HTTP_HOST']);
    }

    public function __toString() {
        return $this->_subdomain;
    }
}

?>
  1. frontend\config\main.php 的“components”部分添加:
    'subdomain' => [
        'class' => 'frontend\components\Subdomain'
    ],
  1. 然后在我需要子域的项目中,我会使用:
$subdomain = \Yii::$app->subdomain;

【讨论】:

  • 我忘了说我使用的是基本模板
  • @IvanWheatman 然后在命名空间中将 'frontend' 替换为 'app',而不是 'frontend' 文件夹放在项目的主文件夹中,如 /var/www/yourapp/components/ 和 / var/www/yourapp/config/
  • 可能我在描述中遗漏了一些东西,或者我们之间有一些误解:) 我不需要使用子域 - 关键是我需要 urlManager 来解析像 这样的链接subdomain.example.comexample.com/index.php/site/subsite?id=subdomain
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
相关资源
最近更新 更多