Routing multiple subdomains using the same CodeIgniter installation

I’ve recently worked on an online portal with product listings for companies. The portal would allow paying customers to have a personalised URL that points to their profile page.

I had already made up a system for users without a personal URL that had the structure “{name}-{id}” so I needed to adapt my URL system to this.

First thing I did was to modify my “application/config/routes.php” file:

// check to see if the link accessed is a subdomain of the main domain
if (substr(strtolower($_SERVER['HTTP_HOST']),-12)=='' && strtolower($_SERVER['HTTP_HOST'])!='') {
    // include a file that keeps track of available URLs 
    // if the subdomain accessed exists in my list, I enable the routing
    if (isset($companies[strtolower($_SERVER['HTTP_HOST'])])) {
        $route['default_controller'] = 'company/index/'.$companies[strtolower($_SERVER['HTTP_HOST'])][0].'/'.$companies[strtolower($_SERVER['HTTP_HOST'])][1];
        // insert other routing rules here
    else show_404();

Now, to explain the “vanity.php” files that I’ve created in the “application/config” folder. I update this file through the registration page every time a user selects a personalised URL.

This is what the file looks like:

$companies = array();
$companies[''] = array(0 => 'Test-company', 1 => 1);
$companies[''] = array(0 => 'Other-company', 1 => 5);

I map the subdomain to the url_title() of the company name and the company id. In this particular example is the same as

This is a solution that is particular to my structure. A simpler way to use this would be to add this in “application/config/routes.php”:

switch ($_SERVER['HTTP_HOST']) {
    case '':
        $route['default_controller'] = "company/index/subdomain";
        $route['default_controller'] = "welcome"; 

One Comment

  1. Not working when use cache.

Leave a Comment

Your email address will not be published. Required fields are marked *