Codeigniter URL Routing, Suffix & Enable Query String
In this tutorial, I’ve tried to give an overview with basic code examples on URL Routing, URL Suffix and URL Enabled Query String. Now the Question is Why it is Required..?? Through CodeIgniter URL Routing a user can present their web page in a more beneficial way, so as to make more sense to visitors and to search engines as well.
By default, URLs in CodeIgniter are designed to be search-engine and human friendly. Through this user actually knows what contents a page contains just by checking the URL in the browser’s address bar.
Hence, URL Routing is a technique which converts these SEO friendly urls to a format that server code can understand easily and drives a request to their corresponding request handler scripts.
Setting Rules For CodeIgniter URI Routing
In order to create your own routing rules, open routes.php located in application/config. Here you will find $routes array which permits you to specify your own routing criteria using any of the two methods given below:
We can use two types of wildcards, namely:
- :num – Segment containing only numbers will be matched.
- :any – Segment containing only characters will be matched.
$route['(blog/:num)'] = 'tutorial/java/$1';
A URL with “blog” as the first segment, and a number in the second will be remapped to the “tutorial” class and the “java” method passing in the match as a variable to the function.
As when we invoke https://www.formget.com/blog/1 or https://www.formget.com/blog/2 it will redirect to https://www.formget.com/tutorial/java/$1.
Note : You can invoke URL only by using number.
$route['(blog/:any)'] = 'tutorial/java';
A URL with “blog” as the first segment, and anything in the second will be remapped to the “tutorial” class and the “java” method.
As when we invoke https://www.formget.com/blog/ or https://www.formget.com/blog/css it will redirect to https://www.formget.com/tutorial/java.
Note : tutorial is controller and java is controller’s function.
Note : Do not use leading/trailing slashes.
You can also redirect your routes using regular expression.
$route['blog/([a-zA-Z0-9]+)'] = 'tutorial/java';
By the above code you can invoke URL by your own regular expression. In this expression special characters are not allowed.
You can also catch a segment containing a forward slash (‘/’), which would usually represent the delimiter between multiple segments.
Note : You can also mix and match wildcards.
To add a suffix, edit config.php which is located in application/config. For example,
$config['url_suffix'] = '.html';
URL Enabled Query String
In order to use Query String URL’s, edit config.php which is located in application/config. Set ‘enable_query_strings’ to TRUE and define controller and function trigger.
$config['enable_query_strings'] = TRUE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm';
This was all about how routes is working in CodeIgniter. Hope you like it, keep reading our other blogs. 🙂