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 🙂

4 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

Comments are closed.