Technical Stuffs

Redirect Old URLs to New URLs

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 https://domain.com/new-url.html
redirect 301 /very-old.html https://domain.com/very-new.html  

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

redirect 301 /file.php?age=old https://domain.com/new-url.html
redirect 301 /file.php?age=old&id=12 https://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 = "https://domain.com/new-url.html";
	break;
	case "/file.php?age=old&id=12";
		$goto = "https://domain.com/im-very-new.html";
	break;
	default:
		$goto = "https://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?

3 Comments

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

  2. Comment by post author

    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. really nice trick 🙂

    thanks

1 Pingback

  1. original site

Leave a Reply