Making Magento load a custom database depending on domain

We needed to make Magento to run a different database depending on the subdomain specified. Here’s how we did it VERY basically. doing so allows you to have separate Magento databases dynamically loaded depending on route. This also makes scaling a lot easier, and usage of systems like beanstalk from Amazon or PHP fog possible.


Keep in mind the following things:

  1. This is not a secure method mentioned below. You should have different passwords for each DB. doing so however will require you to store somewhere the passwords to access.
  2. This was tested on Magento 1.6 CE and 1.11 EE in a unix environment.
  3. This method assumes you don’t store any custom data in the config.xml. You should make your XMLs read-only to ensure this. 
  4. You should spend time with your own environment, so I’m not too specific in these instructions. 
  5. These require some core changes. If anyone has any suggestions on how to do it without the core changes, be my guest and comment below.

The Steps

Step 1: Edit the index.php. Somewhere before loading Magento, pull the subdomain using your favourite method. We used $_SERVER[‘SERVER_NAME’]. Set this to $subdomain.

Step 2: Within index.php, find Mage::run near the bottom. The last paramater allows you to specify custom directories. Make the media and var/ directories custom depending on the domain. We did something like this:

    Mage::run($mageRunCode, $mageRunType, array(
            ‘upload_dir’  => $dir.‘/media/upload’.$subdomain,
            ‘tmp_dir’     => $dir.‘/var/tmp’.$subdomain,
            ‘cache_dir’   => $dir.‘/var/cache’.$subdomain,
            ‘log_dir’     => $dir.‘/var/log’.$subdomain,
            ‘session_dir’ => $dir.‘/var/sessions/’.$subdomain,
            ‘export_dir’  => $dir.‘/var/export’.$subdomain,



Step 3: I know global variables are bad, but set global $subdomain; Now you can access it anywhere.

Step 4: Edit app/code/core/Mage/Core/Model/Config.php or move it to app/code/local/ After line 279, add something like:
     global $subdomain;
       $this->_xml->global->resources->default_setup->connection->dbname = $subdomain;

You may want to also add some checks here to see if the DB actually exists.

Step 5: Edit app/Mage.php and after line 689 add:
       global $subdomain;
       $localConfig->global->resources->default_setup->connection->dbname = $subdomain;
       $xml = $localConfig->global->resources->default_setup->connection->dbname;

Step 6:  Name each new database you create by the subdomain.

Try it out

Try it out. Assuming you’ve done everything correctly you should get Magento to load now depending on the subdomain. Definitely do your own tweaking, but I really hope this helps someone.