CodeIgniter Routes Trick - Removing Controller Names from the URI to Keep URLs Short.

CodeIgniter is great because you can separate your content from your styling with controllers, models, and views. Another great thing is when you create a website with CI, you automatically use friendly URLs (if you use an .htaccess file). If you have a bunch of unrelated pages however, you might wonder how you can keep those URLs as tiny as possible without having thirty different controllers for each page. For example, I have a CI application with a home controller that has about 20 different functions inside of it. To access each one of these functions, I would normally visit http://localhost/home/contact or http://localhost/home/about_us. Since we don’t really need home in the URL, I have found a way to remove it from the URL, still allowing other controllers to function normally. Here’s how to do it:

Open up your routes.php file inside the application/config folder in your CI app and add the following line to the end of the routes.php file:

$route['^(?!ezstore|ezsell|login).*'] = “home/$0″;

This line uses a regular expression that means, If a visitor goes to any url EXCEPT ezstore, ezsell, or login, redirect them to the home controller, and the function inside the home controller ($0). This way, every time we call a function from the home controller, such as contact, about_us, services, etc., we can snip home out of the URL and keep our URLs short and pretty.

The end!



6 Responses to “CodeIgniter Routes Trick - Removing Controller Names from the URI to Keep URLs Short.”

  1. It’s really a great tip! But it could be better if, instead of manually write the exceptions (name of the controllers), it was possible to read the controllers directory and automatically fill the names…

    Do you think it’s possible? Any idea how?

  2. You would have to write a loop before the routes come into play to identify all of the different functions inside the classes. Then, you would have to make sure none of them are named the same or choose a default route if functions are named the same within multiple controllers. Seems like a lot of work! There may be a better way…

    You may be able to just loop through all of your classes and try searching for a function that exists. That would be the easiest route I think. Then, you would just have to specify the names of the controller classes.

  3. Trourbito says:

    Уроки счастья или как встретить свою любовь на Западе
    Расскажет и научит вас вебсайт http://www.mydatelove.com

  4. Ryan says:

    Thanks for this!just what I needed!

  5. nick yeoman says:

    Wow, I was really stuck on my project until I found this, exactly what I needed.

  6. sirviejo says:

    Great tip!

    i will play with routes and then post my experience.

Leave a Reply