RSS

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

Tue, Jul 31, 2007

CodeIgniter, SEO, Web Design, Web2.0

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!

This post was written by:

Daniel - who has written 36 posts on the web developer’s journal.


Contact the author

Leave a Reply