Taking care of the www issue in CodeIgniter


Note: This is a post written on July 24, 2009 in my personal website, Bibakis.com.
It has moved here, mostly for archival.

One of the problems that came up with the rising dependency on Google and SEO in general is the use of www. On the one hand there is no reason to use www anymore. 100% of modern browsers use the HTTP protocol by default so you don’t need to specify that you need to access the web part of a domain. It makes your site’s address larger and harder to remember, more ugly, less likely to fit alongside a logo. Also many suspect that it has an effect on your keyword density, therefore harming your search engine rank just a little bit.

On the other hand most of the users still keep the old habit of typing www.site.com in the address bar. I try to redirect to the “clean” version of the domain on all my sites. Even if the user uses the www he’s not harmed at all.

In fact most of the times nobody even notices. One way or another there is a solution to this. Whether you want to get rid of that 90s annoyance or you want to keep your domain a classic www there is an easy way to do this in codeigniter.

First create a hook in /application/config/hooks.php

$hook['post_controller_constructor'][] = array(
 'class'    => 'Utils_hook',
 'function' => 'redirect_to_base',
 'filename' => 'utils_hook.php',
 'filepath' => 'hooks'
);

This tells CodeIgniter to execute the “redirect_to_base” method before the controller starts executing it’s own methods. Then you need to create the file /application/hooks/utils_hook.php and place the following code inside

Class Utils_hook {
 function redirect_to_base(){
  $ci = & get_instance();
  $uri = $ci->uri->uri_string();
  // recreates the URL
  $location = substr(base_url(),0,strlen(base_url())-1).$uri;

  $active_base_url = 'http://'.$_SERVER['SERVER_NAME'].'/';

  if (($active_base_url != base_url()) && ($_SERVER['SERVER_ADDR'] != '127.0.0.1')){
   Header( "HTTP/1.1 301 Moved Permanently" );
   Header( "Location: $location" );
  }
 }
}

This way the visitor is always redirected to the URL version you want even if he entered through an old bookmark such as http://www.sitename.com/action/example/