I need to redirect all urls like these:
www.example.com/blog.php?id=29
to urls like these:
www.example.com/blog/29/this-is-a-blogpost
Where "This is a blogpost" is the title stored in the database.
Is there a way to rewrite these urls in this way ?
Well mod_rewrite canot query your database and pull the title for the provided id from a DB table.
You'll need to pass id to a server side code (like a php script) in order to fetch & display title.
For ex look at the SO URL for this question: http://stackoverflow.com/questions/17239887/is-there-a-way-to-rewrite-this-url
where it is passing both id and title. So you can have friendly URLs like:
http://www.example.com/blog/29/this-is-a-blogpost
If you decide to go by my suggestion then here is the code you will need in .htaccess:
Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteRule ^blog/([0-9]+)/([^/]*)/?$ /content.php?id=$1&title=$2 [L,QSA,NC]
Then in your content.php
:
<?php
$id = $_GET['id'];
$title = $_GET['title'];
$dbTitle = // get title from Database query using $id
...
if ($title != $dbTitle) {
// redirect with 301 to correct /blog/<id>/<title> page
header ('HTTP/1.1 301 Moved Permanently');
header('Location: /blog/' . $id . '/' . $dbTitle);
exit;
}
// rest of your script
?>
What you ask is obviously impossible: the second url you want to redirect to contains data that is not present (known) in the original request. Where should that data come from inside the redirection process?
The other way round certainly is possible and often done.