Codeingniter: dynamic default controller for multisite

In Codeigniter default controller is set on the routes.php configuration file. Default controller is the controller that handles request when the controller is specified on the url. The main purpose is to open home page.

But sometimes you may want to open multiple different home pages if you have configured your single application to handle multiple sites.

That means you have to set default controller dynamically based on the host url. This can be done directly puting some logic on the routes.php files.

Here is the sample code

$route['default_controller'] = "page";
if (isset($_SERVER['HTTP_HOST'])) {

    if ($_SERVER['HTTP_HOST'] == "links.cp.local:88") {

        $route['default_controller'] = 'link';
    } else {
        $route['default_controller'] = 'page';
} else {
    $route['default_controller'] = 'page';

Another approach is to select the default controller from the database. The table sites has default controller information for each site. On the top of the routes.php file determine the default controller and assign it.

Here is the code

require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$url = $_SERVER['HTTP_HOST'];
$pos = strpos($url, ":");
if ($pos > 0) {
    $url = substr($url, 0, $pos - strlen($url));
$db->where('name', $url);
$q = $db->get("sites");
if ($q->num_rows() > 0) {
    $r = $q->result();
    $dc= $r[0]->defaultcontroller;

$route['default_controller'] = $dc;

Create sites table schema

CREATE TABLE `sites` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL DEFAULT '',
  `title` varchar(100) NOT NULL DEFAULT '',
  `defaultcontroller` varchar(50) DEFAULT 'page',
  PRIMARY KEY (`id`)