Dynamic url rewriting in CodeIgniter
I work with CodeIgniter almost exclusively on API, but sometimes it can help on short-lived websites. Rewrite url is a good thing to know if you want to optimize SEO for your key pages of a website. That’s what I want to show you and how it’s easy to set it up.
Simple url rewriting
A .htaccess file is a configuration file for web server like Apache. Its content includes permission rules for file and directory, configuration rules for HTTP status codes (404 not found, etc) but also url redirections.
At the first install, CodeIgniter is already rewriting url as follow “www.my-website.com/index.php/myController/myMethod”. However, I want to migrate an old website and my actual url is more like “www.my-website.com/news.html”.
Here is my ‘news_controller.php’ file in CodeIgniter
We need now to edit the “config.php” file in “application/config” folder with the following lines:
What does it change? Almost everything: we can now make dynamic url rewriting.
To show our “Hello World”, we had an URL “www.my-website.com/news_controller/sayHello” but now, we can get it with GET params: “www.my-website.com/index.php?c=news_controller&m=sayHello”. For my example, my controller is already in the default directory, I don’t need to use the ‘d’ param.
Now we can add some rules in our .htaccess file, created in the root directory.
If your files are not in the root directory of your server, add your current path in the “RewriteBase” rule (exemple: “RewriteBase /CodeIgniterDemo/” ).
Our new url is now ready to use: we can see our “Hello World” on our new url “www.my-website.com/news.html”.
Dynamic url rewriting
Basically, dynamic url rewriting can be part of a good SEO. It’s also a good way to make your website user-friendliest. It’s easier to understand and remember an url like “www.my-website/product-apple-11.html” than “www.my-website/product.php?id_product=11”.
Here is a part of my ‘roduct_controller.php’:
To finish our dynamic url rewriting, don’t forget to add a new rule in your .htaccess:
Easy, isn’t it? We’ve successfully rewrite our whole website, with static and dynamic url.
Url rewriting is not always necessary, but it can be an easy way to keep your SEO. However, in this post, I don’t talk about the “old way” url: “www.my-website/product.php?id_product=11” and “www.my-website.com/news_controller/sayHello” are alwayse available. Use some security system to “lock” it if needed.
That is my first english post, so let me know if you have any questions / suggestions about it.