maestro416
maestro416

Reputation: 924

How can I customize the URL in the address bar to display the article title?

I'm trying to figure out how to modify a URL in the address bar to show a title for an article.

I have a blog with the posts being pulled from the mysql DB and the links to the detailed view of each blog post is generated as blog_details.php?lesson_id=$articleID. What I can't seem to figure out is how can I rewrite the url to show /article-title/ rather than /blog_details.php?lesson_id=abc and what to do with the new url when retrieving the contents of the post.

I know that if I use

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)$ /blog_details.php?lesson_id=$1

it'll come up as abc but abc is not the title of the post, but rather the ID. Would I need to create a separate column in my db and store the url-article-title in it and just pass that information off into the URL blog_details.php?lesson_id=?

The other question is, in my blog_details.php I'm using if(isset()) {$_GET[]} to retrieve the article ID currently and load the content of the post through that. How would I have to modify the $_GET request to retrieve the new url?

Upvotes: 1

Views: 1373

Answers (2)

Bill Criswell
Bill Criswell

Reputation: 32921

If you want the url to be just /article-title it would be more efficient to add a "slug" column, index it properly and use that to retrieve the entry.

If you'd be ok with a url like /article-title/id you can accomplish that without touching the database. I'm assuming the ID is a number.

RewriteRule ^([^/]+)/([0-9]+)$ /blog_details.php?lesson_id=$2

This is similar to how StackOverflow handles their URLs. You should definitely output the canonical URL on the site to prevent duplicate content because the "title" that's passed won't matter and could get weird. For example: /some-article-title/123 and /some-other-article-title-123 would both bring you to 123.

Upvotes: 2

Ankur
Ankur

Reputation: 169

this is what I normally do in these type of situations. First of all, yes you would need to create a separate column and store the title of the article. Then, using this rule..you can rewrite this :- blog_details.php?lesson_id= to this :- /articles/articletitle

The rewrite rule :-

RewriteRule ^articles/(.+)$ blog_details.php?id=$1 [L,QSA]

Note :- You would need to fetch the url title via the id.

Upvotes: 1

Related Questions