Permanent redirect which is also known as the famous ‘301 redirect’ is one of the most efficient and search engine friendly method for redirecting pages or websites to a different destination. 3o1 redirects can come handy in several situations, such as:

  • to move an old website to a new domain
  • to setup several sites pointing to only one destination website
  • to enforce only one version of your website (www. or no-www) to be used.
  • to harmonize a URL structure change

There are several ways to setup a 301 Redirect, below I will cover the most common ones:

Apache .htaccess Singe Page Redirect

If you would like to redirect your visitors to a different domain, copy and paste the following code in your .htaccess file.

Basically it it will redirect all the visitors accessing http://domain.com to http://www.domain.com.

Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^domain.com [nc]
rewriterule ^(.*)$ http://www.domain.com/$1 [r=301,nc]

PHP Single Page Redirect

In order to redirect a static page to a new address simply enter the code below inside the index.php file.

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.newdomain.com/page.html");
exit();
?>

PHP Canonical Redirect

The Canonical 301 Redirect will add or remove the www prefixes from all the pages in your domain. The code below redirects the visitors of  a non-www version of the page to http://www.domain.com.

<?php
if (substr($_SERVER['HTTP_HOST'],0,3) != ‘www’) {
header(’HTTP/1.1 301 Moved Permanently’);
header(’Location: http://www.’.$_SERVER['HTTP_HOST']
.$_SERVER['REQUEST_URI']);
}
?>