one yii2 code base for multiple domain with different database

What I have right now is

yii2-app1 , yii2-app2 and yii2-app3 are exact the same code

I would like to make a yii2-app and somehow map the domain to its database


  • should use yii2-app1 database and /var/www/yii2-app

  • should use yii2-app2 database and /var/www/yii2-app

  • should use yii2-app3 database and /var/www/yii2-app

Is it possible ?

The easiest way I think is to point domains to the same folder but in the configuration file create a switch checking the called domain name and based on it adding the proper db connection.

thanks @bizley

this is my common/config/main-local.php code. Hope it helps others


if (strpos($_SERVER['SERVER_NAME'], '') !== false) {

    $db = [

        'class' => 'yii\db\Connection',

        'dsn' => 'mysql:host=localhost;dbname=test1',

        'username' => 'test1',

        'password' => 'test1',

        'charset' => 'utf8',


} else if (strpos($_SERVER['SERVER_NAME'], '') !== false) {

    $db = [

        'class' => 'yii\db\Connection',

        'dsn' => 'mysql:host=localhost;dbname=test2',

        'username' => 'test2',

        'password' => 'test2',

        'charset' => 'utf8',


} else {



return [

    'components' => [

        'db' => $db,




Nice and useful article.

But i need to know if this option is possible


Kindly someone let me know if possible.


Murali krishna .L

here is a similar question. You can see my response there too.