I have URL’s like so
mysite.com/view.php?id=123
I have changed the URL’s to look like this with .htaccess
mysite.com/123/page-title.html
Now, since the “page-title” part wasn’t part of the original URL, and is information from a mysql table that corresponds to the id “123”, how can I 301 redirect the old URL’s to the new URL’s ?
Surely there must be some PHP involved, but I don’t know how to write that in .htaccess…
The only rewrite rules you need is to make the nicer looking URL route to
view.php, which it sounds like you’ve already got. Probably looks something like this:When that request gets to
view.phpyou can check the$_SERVER['REQUEST_URI']variable, and it will look like'/123/page-title.html'. When you see that, you know just to serve the content and be done with it.However, when the
view.phplooks at$_SERVER['REQUEST_URI']and it looks like'/view.php?id=123', then you know someone has requested the pagehttp://mysite.com/view.php?id=123and not the nicer looking URL. When this happens, theview.phpneeds to look up the page-title from the database using$_GET['id']‘s sanitized value, then create a redirect (all this needs to happen before anything gets printed to the browser):Something like:
That’ll redirect the browser to the page
http://mysite.com/view.php?id=123. You don’t need anything else in htaccess.