Codeigniter URL Rewriting

Codeigniter URL Rewriting

mostly we need to rewrite URLs to provide user friendly URLs of projects.

In CodeIgniter its much simple rather than manual writing HTAccess Rules.

Suppose you have :

  • Controller (users)
    • Function (index) list of all users
    • Function (add) add user
    • Function (view) view user
    • Function (update) update user information
    • Function (delete) delete user

Normally URLs will be :

  • www.example.com/users/index/
  • www.example.com/users/add/
  • www.example.com/users/view/
  • www.example.com/users/update/
  • www.example.com/users/delete/

But you want that URLs should be:

  • www.example.com/users/
  • www.example.com/add-user/
  • www.example.com/view-user/
  • www.example.com/update-user/
  • www.example.com/delete-user/

You do not need to add HTAccess rules in CodeIgnitor.

Just go to /application/config/routes.php

Aprx line 42

add following lines:

  • $route[‘users’] = “users/index/”;
  • $route[‘add-user’] = “users/add/”;
  • $route[‘view-user’] = “users/view/”;
  • $route[‘update-user’] = “users/update/”;
  • $route[‘delete-user’] = “users/delete/”;

That’s All.

Now you can update your hyperlinks and rewrite rules will be done.

You open path www.example.com/add-user/

it will be opened www.example.com/users/add/

Enjoy 🙂

102 thoughts on “Codeigniter URL Rewriting

  1. Thank You . You saved me from a lot of headache. I preapred myself to spend hours on fixing the htaccess to work on categories and other urls n never knew about routes so far.

    so nice of you and wish you good luck.

    can you let me know if i can route all image requests to a specific folder.

    like should be routed to /assets/images/site/logo.png

  2. Hi thanks for your comments.

    to access images, you can create a function same as base_url() … you can create images_url() and set path in that.

    Feel free to ask queries.

    thanks

  3. Thanks. you saved a lot of time. but i want to make dynamic route paths. like my footer links are dynamic and added/deleted from admin side.Admin created pages and title of these pages will be viewed in footer, admin adds slug for any page (e.g page[‘title’]=’About Us’, page[‘slug’]=’about_us’). Now this slug name will be sent to the controller.How to make url for this type of scenario.

  4. Hi Mobeen, Can you please tell me exact scenario that you have page slug as parameter to a controller’s function something like this domain.com/controller/function/about_us

    or you have a controller for about_us something like this
    domain.com/about_us

    then I can tell you a better answer.

    thanks

  5. Hi Sandeep Barala,

    I am sure this will work.

    $route[‘(.*)/(.*)-(.*)’] = “products/detail/$3″;

    Here :
    first : (.*) -> shows category name
    second :(.*) -> product name
    third : (.*) -> product id

    we will parse third parameter and based on that we can get information of product and then also get category information.

    Feel free to contact if issue not resolved.

    Thanks

  6. You can do like:

    $route[‘shop/result.html?keywords=(.*)&x=(.*)&y=(.*)&catidtobeparent=(.*)&inc_subcat=(.*)&manufacturers_id=(.*)&pfrom=(.*)&pto=(.*)&dto=(.*)’] = “shop/advancesearchresult?keywords=$1&x=$2&y=$3&catidtobeparent=$4&inc_subcat=$5&manufacturers_id=$6&pfrom=$7&pto=$8&dto=$9″;

    And so on.

    Thanks

  7. HI Naveed,

    Actually, i am facing one issue i.e
    I have url like this http://mydomain.com/blog/category/10/category-name
    I want like this http://mydomain.com/blog/category/category-name

    It should work without any change in the coding and my code should read id becuase it display record based on id not by category name.

    Can you help me in this.

    I have tried in the routes.php but nothing happend.

    Can i hide one parameter like this:-
    $route[“category/$2”] = “category/$1/$2”;

    Thanks a lot !

  8. Dear Naveed Ramzan,
    I’m fetching a problem in codeigniter recently.
    I tried it in many ways. used _remap function and route.php as well as some other
    technique but failed. If you have solved this problem please give me the code. It’ll
    help me a lot and save my time.

    I need to rewrite my url in codeigniter dynamically.
    Say my url
    mysitename.com/controller/method/id1.
    mysitename.com/controller/method/id2
    mysitename.com/controller/method/id3
    ………
    mysitename.com/controller/method/idN

    I want to remove method name from url and id would be my variable. Just as follows
    mysitename.com/controller/search-engine-friendly-string1
    mysitename.com/controller/search-engine-friendly-string2
    mysitename.com/controller/search-engine-friendly-string3
    …..
    mysitename.com/controller/search-engine-friendly-stringN

    You are expert in CodeIgniger. I am sure u have the solution.
    Hope I explained the problem. Thanks in advance…

    1. Dear Salsauzzaman Khan,

      you need to write a route line in routes.php

      $route[“controller/user-friendly-url-$1”] = “controller/method/$1″;

      I am sure it will be helpful

      Thanks

  9. it’s not working when i am trying this

    $route[‘default_controller’] = “welcome”;

    $route[“contactus”] = ‘contactus’;
    $route[“content-(.*)”] = ‘content/$1’;

    $route[‘404_override’] = ”;

    1. Dear NoorKhan,

      for default_controller, welcome should be a controller name.

      Same for contactus, it should be controller name

      the method of calling routes is like

      $route[“content-(.*)”] = ‘controller/method/$1’; //$1 is parameter

      Please let me know if you need further assistance.

      Thanks

  10. Dear Naveed
    Thanks for Prompt reply

    welcome is my controller name
    class Welcome extends CI_Controller

    contactus is also my controller name

  11. I am working on localhost

    $route[“content-(.*)”] = “content/page/$1″;

    class content extends CI_Controller {
    public function index()
    {
    //$this->load->model(‘content_model’);
    //$this->load->view(‘content’);
    }

    function page($url_title = ”)
    {
    $id = $_REQUEST;
    print_r($id);
    $this->load->model(‘content_model’);
    $this->load->view(‘content’);
    }
    }

  12. Thanks Above issues has been resolved it was my mistake 🙂

    $route[“contactus”] = ‘contactus’;
    $route[“content-(.*)”] = “content/page/$1”;
    $route[“(.*)-(.*)”] = “brandsdetail/brandprofile/$1”;
    $route[“stores”] = “stores”;
    $route[‘(.*)/(.*)’] = “storedetail/profile/$1”;

    All are working fine when i put last line on route file and then try to execute it’s go to brandsdetail (means it’s execute line 3)

  13. Ok what if you attach word in url.

    Such as :
    $route[“brand-(.*)-(.*)”] = “brandsdetail/brandprofile/$1″;
    $route[“store/(.*)/(.*)”] = “storedetail/profile/$1″;

    brand and store are more seo friendly words.

  14. _remap() is also a powerful function in CI for SEO friendly url. please share some article about it as well.

  15. Hi Nimmy,

    If you try like this.

    $route[‘property_detail/(.*)-(.*)’] = “controller/property_detail/$1/$2″;

    Here $1 will be id
    and $2 will be slug

    both will be tackled in url.

    Id you can pass to controller’s method
    slug will be helpful for SEO Friendly URLs.

    Please let me know if you need more assistance.

    Thanks

    1. $route[‘mobile/nokia’] = “controller/mobile/4″;

      But in this way, nokia will be a slug/keyword while passing in parameter its ID only.

      so best is to pass name instead of id like this

      $route[‘mobile/(.*)’] = “controller/mobile/$1″; // here set variable in where clause

      or you can do like this

      $route[‘mobile/4-nokia’] = “controller/mobile/$1/$2″; // in this way, you can map $1 as ID and second paramter as empty

  16. This was working

    $route[‘(:any)’]= “product/index/$1”;
    $route[‘(:any)’]= “product/view/$1”;

    but when execute last route execute only one execute why ?
    just one function execute
    how i chnage in $route[‘(:any)’] for specific function

  17. Well for the last comment

    $route[‘(:any)’]= “product/index/$1″;
    $route[‘(:any)’]= “product/view/$1″;
    but when execute last route execute only one execute why ?

    Its in fact overwriting.

    you need to give a token or path instead of only :any.

    such as

    $route[‘list-(:any)’]= “product/index/$1″;
    $route[‘detail-(:any)’]= “product/view/$1″;

    for above two comments, I am sure you can fix as my given example.

    or you can send me your effort and i can update you.

  18. Thanks for reply but i can not understand token

    my orignal path is

    http://localhost/pms/product/index/phones/1
    but i want

    http://localhost/pms/product/phones/1

    how your solotion not working i can not understand after your solotion waht was link can you mention please ?

    $route[‘list-(:any)’]= “product/index/$1″;

    what was list and where i use it waht is new link after this because when i add it

    error page was not found

    thanks for your update

  19. this is my rout file

    /* use for admin */
    $route[‘addproductmeta’] = “cms/addproductmeta”;
    $route[‘productinfo/(:num)’] = “cms/productinfo/$1”;

    /* use for web */

    $route[‘default_controller’] = “webmain”;

    /* i change it but it not work */
    /*$route[‘list-(:any)’]= “product/index/$1”;
    $route[‘list2-(:any)’]= “product/view/$1″*/;

    $route[‘404_override’] = ”;

  20. Hi,

    I have a situation where my slideshow displays fine on localhost/citylights/ but when i go to the url: localhost/citylights/en/1/some-page everything displays okay except the slideshow images.

    my .htaccess is:

    # Development
    RewriteEngine On
    RewriteBase /citylights/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond $1 !^(index.php|images|scripts|styles|vendor|robots.txt)
    RewriteRule ^(.*)$ index.php/$1 [L]

    My routes.php is:

    $route[‘default_controller’] = “content”;
    $route[‘en/(:num)/(:any)’] = “content/en/$1”;

    The issue i think is two-fold:

    1. My images display fine when in localhost/citylights/ but not when in the url sub-directory path of localhost/citylights/en/1/ even though i am using base_url() (where base_url is set as localhost/citylights/)
    2. My javascript (that does slideshow) is set with a path of “assets/js/some-js.js” but when i try to set path using base_url() nothing works on anything.

    Therefore path is all correct when in localhost/citylights/ but moment i go to localhost/citylights/en/1/some-page all the paths for the images and js mess up. Any ideas??

    thx

  21. Hello Naveed,

    Great tips on rewriting using Codeigniter.
    I have a different kind of query regarding rewriting URL

    This is the current URL
    http://localhost/mywebsite/page/

    And I want it to work as root url as
    http://localhost/mywebsite

    Which I have already done by adding it as default controller in config.php

    But now I have another URL as
    http://localhost/mywebsite/page/mypagename

    Which should open as
    http://localhost/mywebsite/mypagename

    How can I do it?

    Thanks in advance,
    Aslam

  22. AoA
    i am facing some issue
    i have same function name for both userside and adminside but different controller name .so when i am routing so it all redirect to userside

    Thanks in advance

  23. Hi Naveed,
    How to do if i want this:
    Localhost/ci/index.php/main/wall/username
    to (atleast):
    Localhost/ci/wall/username
    Or (better):
    localhost/ci/username

    Note: username is the parameter where shoud exist in the database. If not exist, the url entered (with or without string username) will directed to “page not found”. Not php error (if username is blank such as localhost/ci/(blank) or localhost/ci/wall/(blank). or mysql error (if the username doesnt exist in the database)

    1. Yes you can do like localhost/ci/wall-username
      and map this in routes.php
      $route[‘wall-(.*)’] = “users/wall/$1”;
      and in function
      public function wall($username){}

      and like this

    1. Well, you can save slug same as wordpress save for pages/posts.

      Like if you save a product

      Epson TM c3510 Color Label Printer so you can save slug epson-tm-c3510-color-label-printer and this slug should be unique.

      and you can pass paramter in URL and get that in controller’s function (as you can see in original post)

      I am sure it will be working otherwise please do email me.
      Thanks

  24. expect create url Like “mobiles?brand=[brand]”
    and wanted to direct the user to brands_mobile/mobile_by_brand
    what would be the route??
    kindly guide me..

    1. Well, you can pass parameter like

      url.com/controller/method/product+name (using url_encode)

      you are passing 1 parameter in function. its name is ID but you can change to NAME.

      in function, you need to search products by name instead of product id. (use url_decode)

      OR

      if you want to make url like
      url.com/controller/method/id-product+name

      then do let me know.

  25. my route file has route[‘(:any)’] = “web/index/$1” to bring URL friendly: localhost/my-slug-url, it works good (am using slugs from database), but my dashboard class does not work if I use the route[‘(:any)’] the problem is that how can I access the dashboard class “dashboard” (has functions add/remove/edit)

    I want to make url : localhost/this-is-my-domain without using route ? the simple I can let you feel my issue is about … and even I can access other class and controller.

    1. $route[‘category/(.*)’] = “category/record/$1″; //here i assume record as function and parameter $1 is the name of category

      as for as about us page
      $route[‘about-us’] = “page/aboutUs″; // here i assume page as controller and aboutUs as function.

    1. In that case you need to set name as unique key or make slug as unique.
      when saving name of institute save also slug. and parse that in URLs.

      $route[‘institute/details/(.*)’] = ‘institutes/details/$1’; // here I am assuming institute as controller and detail as method.

    1. Well, you can set title of product as unique slug :
      $route[‘Snapdeal/(.*)’] = “controller/function/$1″; // here $1 is slug or title of product. and in db you can search product with its slug.

  26. Hello sir i have two controller having name holiday_detail and tour_packages into one floder name frontend and controller routes is

    $route[‘default_controller’] = “home”;
    $route[‘(:any)’] = “holiday/holiday_detail/$1”;
    $route[‘(:any)’] = ‘package/tour_packages/$1’;

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

    1. In fact, you are mapping one url into two paths. You need to set separate url for these two.
      Like
      $route[‘default_controller’] = “home”;
      $route[‘holiday/(:any)’] = “holiday/holiday_detail/$1”;
      $route[‘package/(:any)’] = ‘package/tour_packages/$1’;

      Now both separate urls will be mapped into two separate path.s

  27. 404 page is coming
    after using
    $route[‘animal_28_12/(.*)’] = “animal_28_12/Blogdetails/$1”
    in application\config\routes
    blogdetails is my controller

  28. well, you can use slug like name of news paper is “Express Jobs” and you can make its slug “express-jobs” and in URL you can pass that slug.

    In Controller’s function, you can pass that slug as parameter and update where clause with slug.

    I am sure it will work

Leave a Reply

Your email address will not be published. Required fields are marked *