3

I'm trying to figure out to get a complete clean url for my blog. Right now I have a decent url that looks like this:

http://example.com/post/44/post-name

Here "44" is the Post ID which I use to get the correct post from the database.

But I have seen wordpress blog having url's like this:

http://example.com/post-name

How can this be achieved? as I need the post ID / $_GET['id'] to be able to get the post.

Troels Johannesen
  • 725
  • 2
  • 7
  • 30
  • 1
    There's a few zillion examples of clean url rules on this site.... – Marc B Sep 03 '15 at 21:19
  • Yeah but most just covers basic htaccess redirects... but that won't work for the example above... – Troels Johannesen Sep 03 '15 at 21:20
  • so? a url's a url. you match whatever you want out of the url and build the internal "ugly" url. that's all a clean url is. something for mod_rewrite to tear apart and build a new url for internal use. – Marc B Sep 03 '15 at 21:24
  • Have you heard of URL Re-writting!! – MarmiK Sep 04 '15 at 12:16
  • possible duplicate of [How to do URL re-writing in PHP?](http://stackoverflow.com/questions/1039725/how-to-do-url-re-writing-in-php) – MarmiK Sep 04 '15 at 12:16

2 Answers2

1

You don't necessarily need the id to retrieve the Post. You only need an indexed attribute with unique values.

To achieve this, your Post model needs to have a "slug" attribute. That slug attribute can be based on any other attribute or combination of attributes you choose, but it's usually based on a "name" or "title" attribute.

So to make all this work, when you create a new Post, you need to create a slug from the name/title and store that in the DB, along with the other Post model data. In your controller action you will then retrieve the /slug from the URL and query the db Post data for a Post with the same slug.

You'll also need to figure out to handle duplicate slugs as they need to be unique. Perhaps something like this would work: /slug-2

-2

Make a database table mapping slugs to IDs, then lookup the ID from the slug in the URL.

When a blog is created,

INSERT INTO slugs_postids (slug, id) VALUES (?, ?);

Then when you do a lookup,

SELECT id FROM slugs_postids WHERE slug = ?;

Matt Prelude
  • 912
  • 5
  • 13
  • I would only recommend this approach if you are unable to modify the posts table schema, for example if you are using WordPress. However since you can modify the schema, an extra "slug" column by which to `SELECT` would be better, since the mapping of IDs to slugs is one-to-one. (Edit for clarity - this is the approach of the accepted answer) – Jxx Dec 09 '15 at 13:53