Redirect Old URLs to New URLs

April 3, 2010 | Technical Stuffs | , , ,

When we have a completely new website and uses different CMS, there will be old URLs that already spread everywhere on the Net. Discarding old URLs is not an option because we will lost visitors from search engines. So we must redirect all old URLs into new URLs.

Using redirect in .htaccess is great, but when your old URLs contain question mark, most likely it will fail to redirect.

Following code will work:

redirect 301 /old-url.html http://domain.com/new-url.html
redirect 301 /very-old.html http://domain.com/very-new.html  

But following code will –at least in my case– failed:

redirect 301 /file.php?age=old http://domain.com/new-url.html
redirect 301 /file.php?age=old&id=12 http://domain.com/very-new.html  

Luckily there’s 404 directive from Apache using .htaccess. We can mix the power of custom 404 page with PHP to perform this directions stuff. Here’s how to mix them up:

Create custom 404 page using .htaccess

ErrorDocument 404 /redirect.php

Then create file redirect.php with following contents:

< ?php
$req = trim($_SERVER['REQUEST_URI']);
switch($req){
	case "/file.php?age=old":
		$goto = "http://domain.com/new-url.html";
	break;
	case "/file.php?age=old&id=12";
		$goto = "http://domain.com/im-very-new.html";
	break;
	default:
		$goto = "http://domain.com";
}
header ("HTTP/1.1 301 Moved Permanently");
header ("Location: $goto");
?>

By this method, old URLs that are no longer exist are forwarded to our custom 404 page (named redirect.php) and that redirect.php will bring visitors to new URLs.

Nice, isn’t it?

4 comments

This post has 4 comments, wiiiiii!

  1. Jauhari 04/04/2010 at 04:59

    if we have so many URL? how to do it automatically?

  2. admin 04/04/2010 at 06:31

    I haven’t found an automatic solution for it. Last time I redirected 155 old URLs into new one by creating rule just like sample above, using simple regex and list from XLS file.

  3. Buzzknow 10/11/2010 at 01:24

    really nice trick ๐Ÿ™‚

    thanks

  4. original site 15/10/2014 at 18:32

    original site

    Yeni Setiawan ยป Redirect Old URLs to New URLs

 

Leave a comment

Allowed tags are: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>