Getting Started With CodeIgniter URL Routing


 Getting Started With CodeIgniter URL Routing  
 

In this tutorial, I will try to give an overview on codeigniter url routing. I will also describe the basic implementation technique with necessary code examples where needed. I am assuming you already know about PHP and worked/has knowledge in codeigniter basics. You should also be familiar with how model-view-controller works and how codeigniter url structure works.

What is CodeIgniter URL Routing And Why It is Required?

We all want to show our web page in a more convenient way, so that it can make more sense to visitors(also to search engines, of course). Such as, one should understand in brief what contents a page contains, just by checking out the URL in the browser address bar. If we keep this as it is in a way what can be understood by server scripts(PHP,Asp.NET etc), like as follows, shouldn’t fulfill our goal much:


http://yourdomain.com?p=1


http://yourdomain.com?p=2


http://yourdomain.com?w=30


http://yourdomain.com?z=234

//etc......

From the above links, there is no way to understand what those pages are about. Now, what if it was something like as follows:


http://codesamplez.com/database/codeigniter-activerecord


http://codesamplez.com/programming/regular-expressions-in-php

These are much more meaningful, we can have a brief idea from just seeing the URL. Also, search engines gives some more value compared to the earlier urls, that’s why they are known as ‘search engine friendly URL’. So, whatever reason you choose, it’s always better to use SEO friendly URL always. Ok, now, we have decided to make our site more SE/visitor friendly and want to use these urls. Now, how we should develop our application to map this urls to original request handler scripts?

Url Rewriting/Routing actually is the technique which converts this seo friendly urls to a format that server code can understand easily/drives a request to their corresponding request handler scripts.

Url Rewriting/Routing Techniques

HTTP Server,(IIS,Apache) provides some ways/programming syntax with which URL Rewriting are done. In Apache web server, htaccess programming technique has some ways to do this routing. However, htaccess isn’t very much easy to consume, specially for the beginners, even apache mod_rewrite documentation , there it is mentioned that “mod_rewrite’s major drawback is that it is not easy to understand and use for the beginner” . Also, to understand this a little better, you will need to understand regular expression basics as well, as most of the htacess rules are written in regular expression format.

Another way is to process the url from the server script itself. we can take primary help from server to forward all request to a specific server script, where with our programming skills, we will parse the urls and process them accordingly. however, that one will not be a very easy task as well. However, on cms and frameworks, there are some integrated functionality to do that works. Codeigniter, is also provide a very good convenient and easy way with rich customizable facility to implement this routing on our application.


Read The Complete CodeIgniter Tutorials Series By CodeSamplez.com

Routing URLs with Codeigniter:

In this tutorial, we will first send all requests to a single controller method on our codeigniter application, where most of the requests should go, and will rout other requests to their specific controller methods. Just make sure, your server is apache and has mode_rewrite mode installed and enabled, then you can use the following code snippet to make it easier to rewrite all server requests by mapping them to a single controller method(you won’t have to learn htaccess for this):

<IfModule mod_rewrite.c>
    
    RewriteEngine On
    RewriteBase /

    # Disable rewrite for valid directory/files	    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d	

    #map all request urls to a specific controller method
    RewriteRule ^(.*)$ index.php?/{controller}/{method}/$1 [L]
</IfModule>

Now, all requests are going to be sent to your specific controller’s specific method as function parameter.

Now, we will want to separate some requests and redirect them to their own corresponding controller/method. To make this happen, please go the file ‘{root}/system/application/config/routes.php’ and open it. At the bottom of the pages, you will have to add the routing rules, with which your want the requests to be routed. Here are few types of rule samples for routing:

//For pages those have a static name
$route['{default_controller}/{default_method}/about.html'] = "{original_controller}/{original_method}";

//rule to rout request with number values
$route['{default_controller}/{default_method}/(:num)'] = "{original_controller}/{original_method}/$1";

//rule to rout request with regular expression values
$route['{default_controller}/{default_method}/([a-z]+)-{delimiter}'] = "{original_controller}/{original_method}/$1";

Dash based URLs To Underscore Based Function:

Well, there is a common problem, that beginners fell most often in working with codeigniter url routing. That is, a controller function name can contains underscore, but not ‘dash’ character, which is very common use in now-a-days web application. So, a requirement of map those ‘dash’ based url name into ‘underscore’ based controller function name comes in the way naturally. To get a robust solution for this, add a new class in your ‘application/core’ directory as follows:

<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class MY_Router extends CI_Router 
{
    function _set_request ($seg = array())
    {
        // The str_replace() below goes through all our segments
        // and replaces the hyphens with underscores making it
        // possible to use hyphens in controllers, folder names and
        // function names
        parent::_set_request(str_replace('-', '_', $seg));
    }
}  

you won’t have to do anything else additionally. it will be automatically loaded by codeigniter and will be in action for any urls.

References

As you are a ci developer, you already know that, there is a very rich, easy to understand documentation on Codeigniter’s functionality, it also has well described documentation on codeigniter url routing as I mentioned above. Also, if your need doesn’t fulfill with any of them(my article and codeigniter documentation), please mention it here so that I can come to know and I will try my best to find a solution. Happy coding :)

Comments

  1. Alex says

    Hi I have working on a project in codeigniter where my categories URL are working “index.php?category=T2″ but i want to rewrite them like as “category-T1-Address+Labels.html”.But i am unable to fix them.Can you please help me how i can route them through routes.php

  2. says

    Hi – I understand what you’ve written (thanks for the tutorial by the way) but isn’t this the point of the routes.php file in the config folder??

  3. says

    Hi Ali,

    thank you for the post. I am new to codeignitor. I am able to use the code for static urls, like

    $route[‘aboutus\.html’] = “aboutus/index”; // ci/index.php/aboutus.html
    $route[‘reachus\.html’] = “reachus/index”; // ci/index.php/reachus.html

    But how to do it with urls some thing like

    http://localhost/ci/index.php/college?cid=38
    http://localhost/ci/index.php/college?cid=40

    I want the above urls to be made like this

    http://localhost/ci/index.php/college/some-college-name

Trackbacks

Leave a Reply