301 Redirection Codes

A collection of the most common methods for performing 301 redirects:

Redirect with .htaccess and Mod_Rewrite

301 Redirect: xyz-site.com to www.xyz-site.com

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

301 Redirect: www.xyz-site.com to xyz-site.com

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^xyz-site.com$ [NC]
RewriteRule ^(.*)$ http://xyz-site.com/$1 [L,R=301]

301 Redirect: Redirecting Individual pages

Redirect 301 /previous-page.html http://www.xyz-site.com/new-page.html

* These scripts should be placed in the .htaccess file.

Redirect with PHP

<?php
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://www.xyz-site.com" );
exit(0);
?>

* This script should be the first piece of code on the page to function correctly.

Redirect with classic ASP

<@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently" Response.AddHeader "Location",
" http://www.xyz-site.com"
%>

* This script should be the first piece of code on the page to function correctly.

Redirect with ASP.NET

<script>
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.xyz-site.com");
}
</script>

* This script should be the first piece of code on the page to function correctly.

Redirect with ColdFusion

<cfheader statuscode="301" statustext="Moved permanently">
<cfheader name="Location" value="http://www.new-xyz-site.com/">

* This script should be the first piece of code on the page to function correctly.

Redirect with Perl

[perl]
$q = new CGI;
print $q->redirect(" http://www.new-url.com/ ");
[/perl]

* This script should be the first piece of code on the page to function correctly.