I want to get the slug even if only the id is supplied. For example I enter this:
http://stackoverflow.com/questions/6421212/
After the site has been loaded, the URL becomes:
http://stackoverflow.com/questions/6421212/how-to-rewrite-url-with-post-title-slug
What I mean is that that I want to pull up the slug even if I only entered the Id.
Thanks in advance!
mod_rewrite does not know the right slug for the given ID. Your application that generates the slug does. So you grab the slug from the database using the ID and compare it with the one sent by the browser. If it does not match, issue a 301 redirect to the full (if slug was empty) or correct (if the slug did not match) URL. That's how SO works. Open these URLs and look at the net inspector to see what I mean:
http://stackoverflow.com/questions/9393455/
http://stackoverflow.com/questions/9393455/foo-bar-blah-baz
In PHP, inspect the $_SERVER
super global, you should be able to find the variables that contain the actual URL before re-writing. And you can send 301
header like so:
header("Location: /1234/correct-slug", true, 301);