I recently had the need to manage multiple host names within a single instance of CodeIgniter. Setting the virtual hosts to all point to the same directory in the web root was the easy part. Intelligently routing the requests, once they got to CodeIgniter, such that I can be sure a domain has its own group of controllers, not so much.

To better illustrate what I am going for, let's say you had 3 different host names that you wanted to all go to your one instance of CodeIgniter:


Now let's say you want to route requests for each of these host names to their own group of controllers:

-- controllers
---- admin
------ api
-------- users.php
-------- items.php
------ home.php
------ shop.php
---- shop
------ api
-------- cart.php
------ catalog.php
---- home.php

The Solution

Hooks! The way I made all of this work was by utilizing CodeIgniter's hook system to trick CodeIgniter's routing methods into mapping a request for a specific domain to its corresponding controller group. I also had to add an additional hook to restore the original URI information from the actual request; so that I wouldn't have to rewrite any of the code in my controllers.

I moved the code to a Gist:


The comments in the files of the Gist should be sufficient to guide you with the set up / configuration.

I had to go one step further for this solution to work 100% for my situation; I needed controllers in sub-sub folders to work.

If all is well, you should now be able to assign any number of host names to your single instance of CodeIgniter and have those requests routed to the controller group of your choice. Fun, huh?