Search code examples
phpurlrenameslug

When the slug of a page changes, external links no longer work. What are the best workarounds?


Let's say I have this URL:

http://example.com/title-of-the-post

When the post title is updated, the URL becomes:

http://example.com/updated-title-of-the-post

Which is ok, except for the links that people have bookmarked, or the links that come from external websites, etc.

I know adding an ID to the URL would be an easy solution:

http://example.com/57884-updated-title-of-the-post

But let's say, I don't want that. The solution I'm thinking about is to keep record of all title updates in the database and match against these if one title is no longer available.

What's the best solution?


Solution

  • There is no 'best solution', but one way to do it would be to have a posts and a slugs table. store the current slug id in the posts table, and store all slogs, with a reference to their owning post_id in the slugs table

    Posts table:

    id | slug_id |othercolums...
    1    3         ...
    

    Slug table

    id | post_id | slug
    1    1         first-title
    2    1         second-title
    3    1         current-title
    

    As a bonus, when you retrieve a post via its slug, you can check if the slug_id on the post matches the searched slug id, and if not perform a 301 redirect to the current slug url.

    That way search engines should update their records.