Apr 15 2008

PHP and .htaccess 301 redirect

Classified in: PHP,Web developmentpaomic at 9:17 am

What is 301 redirect ?

A 301 redirect is a way of telling a broswer (and a search engine spider too) that a page has moved (301 http code means permanent redirection). This is useful in case you moved a website to a new domain or if you want to hide your dynamic page extension (i.e. show mypage.htm instead of mypage.php or mypage.aspx).

When do you need 301 redirect ?

As already stated, 301 redirect can be useful for moved pages, to redirect users from yoursite.com to www.yoursite.com, to hide extensions, to redirect from for example page-1.htm to index.php?page=1 (if you want to remove long urls and let them appear as plain htm pages) and more!

How to 301 redirect in PHP ?

To redirect a single page to a new localtion:

<?php
header(’HTTP/1.1 301 Moved Permanently’);
header(’Location: http://www.yourdomain.com/newpage.php’);
?>

If you want to add the www at the beginning of the site url

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 301 redirect in .htaccess file?

To redirect pages you cal also use htaccess file, only if you’re using n Apache webserver. In this case, simply create a file namd .htaccess (note the dotat the beginning) and put it in the root directory of the website (note that your FTP client may hide this file, so check the docs and find out how to show all files, usually adding -aL to the FTP client options).

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

Tags: