Redirect Non-WWW to WWW using htaccess

February 16, 2012 | Technical Stuffs | ,

I’m using this script very often, for some customers to redirect their website from domain.com to www.domain.com. So I will put it here for easy access.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Just create or insert above script into your .htaccess. When a visitor visits domain.com he will be forwarded to www.domain.com.

Piece of cake.

1 comment


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