Load a different config based on hostname

I would like to load a different config file depending on the domain name that the application is running on.

Where is the best place to put this logic?

My suggestion will be in Index.php in protected folder…

A lot of people are splitting up their configs into several files and join them via CMap.mergeArray(). You could do the same with your config. Just move your config/main.php to config/_defaults.php and create a new config/main.php like this:




<?php

if(file_exists('config.' . $_SERVER['SERVER_NAME'] . '.php'))

  return CMap::mergeArray(

    require('_defaults.php'),

    require('config.' . $_SERVER['SERVER_NAME'] . '.php')

  );

else

  return require('_defaults.php');



You can do it yourself, or you can use a fantastic extension yii-environment for that. You can easily add new environments and that can be domain1, domain2 etc. Extension will take care of choosing right config files. Since chose is based on environment variables you can just set right one in .htaccess.


IndexIgnore */*

RewriteEngine on


#we want to clean url from index.php

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php


#needed for yii-environment extension to choose right config file

RewriteCond %{HTTP_HOST} ^domain1.*

RewriteRule ^ - [E=YII_ENVIRONMENT:DOMAIN1]

RewriteCond %{HTTP_HOST} ^domain2.*

RewriteRule ^ - [E=YII_ENVIRONMENT:DOMAIN2]