
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 Is It Required?
We all want to show our web page in a more convenient way so that it makes more sense to visitors(and to search engines, of course). For example, one should understand in brief what content a page contains just by checking out the URL in the browser address bar. If we keep this as it is in a way that can be understood by server scripts(PHP, Asp.NET, etc), like as follows, it 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......
Code language: JavaScript (javascript)
From the above links, there is no way to understand what those pages are about. Now, what if it was something like the following:
https://codesamplez.com/database/codeigniter-activerecord
<blockquote class="wp-embedded-content" data-secret="ww8oEBqEXL"><a href="https://codesamplez.com/programming/regular-expressions-in-php">Beginners Guide To Use Regular Expression In PHP</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted" style="position: absolute; visibility: hidden;" title="“Beginners Guide To Use Regular Expression In PHP” — CODESAMPLEZ.COM" src="https://codesamplez.com/programming/regular-expressions-in-php/embed#?secret=GoOJWS0mSL#?secret=ww8oEBqEXL" data-secret="ww8oEBqEXL" width="500" height="282" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
Code language: JavaScript (javascript)
These are much more meaningful, we can have a brief idea from just seeing the URL. Also, search engines give more value than earlier URLs, which is why they are known as ‘search engine friendly URLs’. So, just as companies like Victorious recommend, whatever reason you choose, it’s always better to use SEO-friendly URLs. Ok, now, we have decided to make our site more SE/visitor-friendly and want to use these URLs. Now, how should we develop our application to map this url to the 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 is done. In the Apache web server, the access programming technique has some ways to do this routing. However, “htaccess “isn’t very easy to consume, especially for 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 get primary help from the server to forward all requests to a specific server script, where, with our programming skills, we can 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 is some integrated functionality to do that work. Codeigniter also provides a very good, convenient and easy way with the 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 route 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>
Code language: PHP (php)
Now, all requests are going to be sent to your specific controller’s specific method as a 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 to 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 you want the requests to be routed. Here are a 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";
Code language: PHP (php)
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 contain an underscore but not a ‘dash’ character, which is very common use in nowadays web applications. So, a requirement of mapping those ‘dash’ based URL names into ‘underscore’ based controller function names 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));
}
}
Code language: HTML, XML (xml)
You won’t have to do anything else additionally. It will be automatically loaded by the 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 isn’t fulfilled 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 🙂
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.
thnx 4 such info
Thanks, I just use in my codeigniter website and my product..
Nice information bro i will use it my next pro… 🙂
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
Try this on httaccess:
RewriteRule ^category-(.*)\.html$ index.php?category=$1 [L]
I am new developer to codeigniter php framwork. It’s very helpful for me.
right this very help full
I used this but my css is breaking.
css and js not getting applied. pl let me know a solution.
Please share in detail about what issue you are having.
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
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??
Yes, it is indeed, that’ what it explains! But what is your question is actually, please clearly mention.
Benig trying to understand routing in codeigniter
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
$route[‘college/some-college-name’] = ‘foldername/classname/method’;
i want to change my blog url after signup page from localhost/login/login_model into ocalhost/somename can any one give me solution
…its very helpful…isn’t there any way besides this one…any how its too good…
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?
Hi coyubaldo,
did you get resolve this problem?
i am also facing this, could you please tell me the solution.
Thanks in advance!
MK
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
Hi that was usefull information i tried it for my project but it is not working please help me out here
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 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:localhost/CodeIgniter/sitef/model/44/angelina#http://localhost/CodeIgniter/uploads/44/general/woman_with_colorful_flowers_197933.jpg
i wanted it to be like localhost/CodeIgniter/sitef/model/angelina/woman_with_colorful_flowers_197933.jpg
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
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!
You should show the comment DSEC order Last comment as first.
Thanks
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 ,
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
Its not working for me. Page showing 404 error
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.
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