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...
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 ?
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:
RewriteCond %{REQUEST_FILENANE} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9]+)/([^/]+)\.html /view.php?id=$1 [L]
When that request gets to view.php
you 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.php
looks at $_SERVER['REQUEST_URI']
and it looks like '/view.php?id=123'
, then you know someone has requested the page http://mysite.com/view.php?id=123
and not the nicer looking URL. When this happens, the view.php
needs 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:
header('HTTP/1.1 301 Moved Permanently');
header('Location: /' . $id . '/' . urlencode($page-title) . '.html');
exit();
That'll redirect the browser to the page http://mysite.com/view.php?id=123
. You don't need anything else in htaccess.
check out this tutorial. It should explain it all very easily.