Is there a way (via routing) in CodeIgniter to change:
example.com/category/4
to example.com/category/foo-bar
where Foo Bar
is the name of category 4
in the database?
Access from the SEO-friendly URL should be allowed, but access via the integer should cause a 404 error.
This should also work dynamically, where any integer is automatically converted to a URL-safe version of its corresponding category name.
I've seen a few solutions that use 'slugs'... is there a decent alternative?
Thanks.
I've only been working with CodeIgniter for the past couple of months in my spare time, so I'm still learning, but I'll take a shot at this (be gentle):
There is a
url_title()
function in the URL Helper (which will need loaded, of course) that will changeFoo Bar
tofoo-bar
.http://codeigniter.com/user_guide/helpers/url_helper.html
The URL helper strips illegal characters and throws in the hyphens by default (underscores, by parameter) and the
TRUE
parameter will lowercase everything.To solve your problem, I suppose you could either do a
foreach
statement in your routes.php file or pass theurl_title()
value to the URL, rather than the ID, and modify your code to match theurl_title()
value with its category name in the DB.Afaik the link between 4 and "foo-bar" has to be stored in the DB, so you'll have to run some queries. This is usually not done via routing in CI. Also routing just points a URL to a controller and function and has little to do with url rewriting.
Why don't you want to use slugs?
Is there a way (via routing) in CodeIgniter to change:
example.com/category/4 to example.com/category/foo-bar
where Foo Bar is the name of category 4 in the database?
Yes.
Using CI 3, http://www.codeigniter.com/user_guide/general/routing.html
Use Callbacks, PHP >= 5.3
You can route to call a function to extract the name of the category.
Hope I answered your question and can help more people to like codeigniter as I believe it's speedy and light.
Slugs usage is important to make web application more secure which i think is important.
A better recommendation will be to use route to give you a better solution.
or
how to modify routes in codeigniter
Have fun :)
You could try storing the search engine friendly route in the database using this method or this one.
I wouldn't recommend throwing a 404. Use the canonical link tag in the instead if your worried about Google indexing both http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html.
But if you really want to I guess you could write a function that is called during the pre_controller hook http://codeigniter.com/user_guide/general/hooks.html that checks to see if the URL has an integer as the second segment then call the show_404() method. Perhaps a better solution when writing this function would be to redirect to the SEO friendly version.