301 redirect in PHP and .htaccess

July 27, 2009 | In: htaccess, php

What is 301 redirect ?

You have a website and its all pages are ranked in the search engine. And now you’ve moved these files to a new domain. What will happen in this scenario!!. You are sending the visitor to “Error 404 – File not found” page when they follow your website in the search engine. Furthermore, if you place the custom error page, then also you will be keep loosing ranking in upcoming days in search engines as the original file could not be found in the old URL. So what is the solution for this?? The solution is 301 redirect which means moved permanently. It is is the most efficient and search engine as well as visitor friendly method for the webpage redirection.

Why do you need 301 redirect ?

Have you ever typed yahoo.com in your browser, what happens next is it will redirect you to www.yahoo.com, its all the result of the 301 redirect. so, why do you need to do so?. If you’re not doing so, then you’re splitting yourself to two different URL and search engine spiders can also crawls your site’s content by two different URL which may result to “duplicate content” penalty by search engines if search engines collect two copies of the same data from two different URLs.

How to do 301 redirect in PHP ?

If you want to redirect a single page to another location then put the following code in the old page which have been moved.

<?php
 header('HTTP/1.1 301 Moved Permanently');
 header('Location: http://www.new-domain.com/new-file-name.php');
?>

If you want to redirect non-www to www domain name then put the following code into top of every page of the website

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

How to do 301 redirect in .htaccess file?

Put the following code into the .htaccess file and upload it into the root folder of the website. Note that this file only works for the website which is running under Apache Web Server.

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