3

I am building a website with codeigniter and my urls follow this format: link1 where the id e.g. 123 is used to query the database for a record.

The last uri segment is just for SEO friendly purposes and can be changed to anything - e.g. link2

Following on from this answer, how can I redirect all variations of the url to display the correct text in the last segment?

Should I check the url is the correct format in my controller and redirect it there?

e.g.

if($this->uri->rsegment(4, 0) !== $this->myModel->recordName) {
    redirect($id.'/'.$this->myModel->recordName);
}

Thanks

---UPDATE1---

Just found a problem with the above method. Sometimes I will have extra segments on the end of the urls - e.g. link - and this won't work with that

---UPDATE2---

Here is my latest code. This ignores additional segments and works if just the id is provided. Hoping someone can confirm if this is the right/best way to do it!

$correctRecordName = myEncodeForUrlFunction($this->myModel->recordName);
$rsegments = $this->uri->rsegment_array();

    if(count($rsegments) < 4 || $rsegments[4] !== $correctRecordName) {
        $rsegments[4] = $correctRecordName;
        $url = site_url($rsegments);
        redirect($url, 'location', 301);
    }
Alyona Yavorska
  • 569
  • 2
  • 14
  • 20
fxfuture
  • 1,910
  • 3
  • 26
  • 40
  • If your already storing the correct url slug (recordName) in the database, why not use that to lookup the data instead of the id? You could remove the ID's, making the urls even cleaner, and you would have no trouble with duplicate content. – Jeemusu Jul 30 '13 at 04:17
  • Thanks Jeemusu - the problem with that is a lot of my record names have special characters and I'm using CI's url_title to encode them. There wouldn't be any way to decode them after that as it just removes the special characters. I could use urlencode but then I'd have nasty urls e.g.%21%40%23%40%40%21 – fxfuture Jul 30 '13 at 04:27
  • In that case your approach should work fine. Why won't it work with the extra segments? If your retrieving the url with `$this->uri->rsegment(n)` it should only return segment n (name-of-the-record) and not the segments n+1 n+2 (urikey, urivalue)? – Jeemusu Jul 30 '13 at 04:39
  • I had to tweak it. Now it ignores extra segments - updated my answer – fxfuture Jul 30 '13 at 05:15

1 Answers1

0

Why don't you just use $this->uri->segment(#); where # is the segment number. This hasn't failed us yet. Also found a few references that suggested rsegment(s) can be buggy.

TotaliNZ
  • 21
  • 2