M. Esmaeili
M. Esmaeili

Reputation: 75

How to create a beautiful post links without ID

I have a link like this:

 http://localhost/mywebsite/post.php?title=my-post-title&id=2

Or

 http://localhost/mywebsite/post/my-post-title/2/  

(using mvc)

But I need to show links without ID, Like many sites on the Internet.

ex:

 localhost/mywebsite/post/my-post-title/

Upvotes: 2

Views: 207

Answers (2)

AndrewL64
AndrewL64

Reputation: 16311

You need to use mod_rewrite to beautify your URLs. Check this link out: http://www.sitepoint.com/guide-url-rewriting/

Here is an example mod_rewrite for above:

RewriteEngine on

RewriteRule ^mywebsite/(.*)/(.*)$ mywebsite/post/?title=$2 [QSA]

Via - How to beautify the URL?

Upvotes: 5

Michael
Michael

Reputation: 12806

The URL must contain a unique identifier. Without it there is no way for your application to know which post to show. In this case you need to create a second unique identifier for your post (in addition to the integer ID): this is called a slug.

So, in addition to the id and title columns add a slug column with a UNIQUE key. This column should be a URL-safe string conversion of the post title (e.g. a title of "This is my first post!" could give a slug of "this-is-my-first-post"). This may require prepending an extra character (or more) if the slug is already in use, i.e. if you have two posts with the title "This is a post" then the first will have the slug "this-is-a-post" and the second will have the slug "this-is-a-post-2".

Once the slug has been created and assigned to the post this will then be used as the identifier in the URL. Using mod_rewrite you'll rewrite http://localhost/mywebsite/post/my-post-title to http://localhost/mywebsite/post.php?slug=my-post-title and then query the database for the post where slug = $_GET['slug'].

Upvotes: 2

Related Questions