• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / Getting Started With CodeIgniter URL Routing

Getting Started With CodeIgniter URL Routing

January 22, 2011 by Rana Ahsan 30 Comments

Codeigniter Tutorials

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:

Codeigniter Active Record Class Overview
Beginners Guide To Use Regular Expression 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 just how companies like Victorious recommend, 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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: codeigniter, php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. umer singhera says

    June 27, 2011 at 2:52 am

    thnx 4 such info

    Reply
  2. hadinug says

    July 6, 2011 at 9:06 am

    Thanks, I just use in my codeigniter website and my product..

    Reply
  3. Sanjeev VIshwakarma says

    April 20, 2012 at 4:58 am

    Nice information bro i will use it my next pro… 🙂

    Reply
  4. Alex says

    December 26, 2012 at 8:50 am

    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

    Reply
    • Md. Ali Ahsan Rana says

      December 26, 2012 at 9:52 am

      Try this on httaccess:

      RewriteRule ^category-(.*)\.html$ index.php?category=$1 [L]

      Reply
  5. razibul hasan says

    August 3, 2014 at 11:21 pm

    I am new developer to codeigniter php framwork. It’s very helpful for me.

    Reply
    • raj says

      February 15, 2018 at 5:21 am

      right this very help full

      Reply
  6. Ajinkya says

    September 6, 2014 at 4:36 am

    I used this but my css is breaking.
    css and js not getting applied. pl let me know a solution.

    Reply
    • Md Ali Ahsan Rana says

      September 8, 2014 at 10:06 am

      Please share in detail about what issue you are having.

      Reply
  7. atul kumar sharma says

    September 27, 2014 at 7:40 am

    hi my url is http://www.onlinenifm.com/module_detail/1/NIFM-Certified-Smart-Investor

    when some one remove the nifm-cerified-smart-investor the page will remain because of id i want only title on this url not a id i try your rout fuction and .htaaccess but not working

    Reply
  8. Tom says

    November 3, 2014 at 9:47 am

    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??

    Reply
    • Md Ali Ahsan Rana says

      November 7, 2014 at 9:59 pm

      Yes, it is indeed, that’ what it explains! But what is your question is actually, please clearly mention.

      Reply
  9. mezie says

    November 13, 2014 at 9:39 am

    Benig trying to understand routing in codeigniter

    Reply
  10. goskula says

    November 18, 2014 at 2:25 pm

    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

    Reply
    • kasthuri says

      January 29, 2015 at 1:46 am

      $route[‘college/some-college-name’] = ‘foldername/classname/method’;

      Reply
  11. nutan says

    December 1, 2014 at 6:49 am

    i want to change my blog url after signup page from localhost/login/login_model into ocalhost/somename can any one give me solution

    Reply
  12. rahamsher says

    December 11, 2014 at 11:40 pm

    …its very helpful…isn’t there any way besides this one…any how its too good…

    Reply
  13. coyubaldo says

    January 7, 2015 at 12:49 am

    hi im just starting to use codeigniter and i cant seem to take out the index.php on my url.

    “localhost/codeigniter/index.php/pages/view”

    im trying to follow the tutorial on the ci site and i want it to look like

    “localhost/codeigniter/pages/view”

    i have this on my .htacess file as instructed in the tutorial

    “RewriteEngine on

    RewriteCond $1 !^(index\.php?|images|robots\.txt)
    RewriteRule ^(.*)$ /index.php?/$1 [PT,L]”

    but still it doesnt work. Any help please?

    Reply
    • Kamal says

      May 21, 2016 at 6:31 am

      Hi coyubaldo,

      did you get resolve this problem?
      i am also facing this, could you please tell me the solution.

      Thanks in advance!

      MK

      Reply
  14. attalink786 says

    March 5, 2015 at 2:50 am

    sir i have two controller having name home n blog_post into one floder name frontend and controller routes is
    $route[‘default_controller’] = “frontend/home”;
    $route[‘(:any)’] = “frontend/home/$1”;
    $route[‘(:any)’] = ‘frontend/blog_post/$1’;

    whats problem in this route??because only blog_post controller method working fine but home controller method not show the page??please help me

    Reply
  15. Manoj Rammurthy says

    October 1, 2015 at 12:30 pm

    Hi that was usefull information i tried it for my project but it is not working please help me out here
    http://localhost/CodeIgniter/sitef/model/43/brunet
    this the url where sitef is the controller , model is the function and 43 and brunet are the parameters to it

    now i want the url to look like http://localhost/CodeIgniter/sitef/model/brunet how to achieve this

    also

    i am using jquery plugin to show gallery it shows the complete path of the image how to get rid of it
    ex:http://localhost/CodeIgniter/sitef/model/44/angelina#http://localhost/CodeIgniter/uploads/44/general/woman_with_colorful_flowers_197933.jpg

    i wanted it to be like http://localhost/CodeIgniter/sitef/model/angelina/woman_with_colorful_flowers_197933.jpg

    Reply
  16. COCL says

    January 4, 2016 at 6:30 am

    Hi,

    $config[‘base_url’] = ‘http://localhost/test/ebayar/tempah2/’;

    how to submit form example:
    form action=”http://localhost/test/ebayar/tempah1/index.php” method=”post”

    if i change $config[‘base_url’] to ‘http://localhost/test/ebayar/ it will be messed up because all the files are within tempah2 folder

    Please help

    Reply
  17. Pardeep Sharma says

    January 14, 2016 at 4:14 am

    Hello,

    I have queries about remove the controller name and method

    domain.com/front/view/about-us

    I want remove front and view from url can you please help me solve this issue?

    Thanks in advance!

    Reply
  18. Rahul Kumar says

    August 17, 2016 at 6:35 am

    You should show the comment DSEC order Last comment as first.
    Thanks

    Reply
  19. kp arora says

    September 21, 2016 at 3:20 am

    I tried to rewrite url using routing and it works now I want to encode id in the url , suppose I have localhost/staff/12 , I want to make it non readable for users . Let me know how can I change it ,

    Reply
  20. Wiki says

    October 22, 2016 at 2:34 pm

    Hi I have working on a project in codeigniter where my categories URL are working “category/4” but i want to rewrite them like as “category/SomeText”.But i am unable to fix them.Can you please help me how i can route them through routes.php

    Reply
  21. Arya says

    December 28, 2016 at 7:07 am

    Its not working for me. Page showing 404 error

    Reply
  22. Robert says

    June 4, 2017 at 4:48 am

    Hello,
    Can you kindly confirm this is valid for codeigniter 3.x?

    If it is not, can you kindly edit the post to add the codeigniter 3.x differences and or requirements?

    Thank you

    R.

    Reply
  23. virender says

    June 18, 2019 at 8:52 am

    hi, i have a problem in my website, my website structure is http://loclhost/wedding/home/contact_us and i want to convert it to http://loclhost/wedding/contact-us. kindly suggest me what can i do. using codeignitor 3

    Reply

Trackbacks

  1. Getting Started With Apache Htaccess Rewrite | codesamplez.com says:
    February 17, 2011 at 10:00 am

    […] framework and having trouble with url rewriting/routing, you can refer to my another tutorial on codeigniter routing). If we need to get work a query string to feed in a specific controller function then, we will […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023