How to do 301 redirects in Apache .htaccess, IIS, PHP, ASP and ColdFusionApache Web Server .htaccess fileApache .htaccess files let you override the Web server configuration on a per-directory hierarchial basis, and are instrumental in the creation of proper 301 redirects. For more information, consult the Apache .htaccess Tutorial and the Apache URL Rewriting Guide.Single Page Redirect:
Redirect 301 /old/url /new/url
or Redirect Permanent /old/ur /new/url Canonical Hostname Redirect (non-www to www):This solution will redirect any page requested via a non-www domain to the same URL with the www domain, and as such it can be placed in the DocumentRoot of your site and will be enforced globally:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com RewriteRule (.*) http://www.domain.com/$1 [R=301,L] Microsoft IIS Web ServerNote: these instructions require administrative access to IIS. If you do not have this access (e.g., if you have a shared hosting account on a Windows server), you should use one of the server-side scripting methods such as ASP or PHP given further below.Single Page Redirect:
PHP 4 and PHP 5Single Page Redirect:
<?php
header('HTTP/1.1 301 Moved Permanently'); header('Location: http://www.new-url.com/'); ?> Canonical Hostname Redirect (non-www to www):
<?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']);
}
?>
Active Server Pages (ASP)Single Page Redirect:
<%
Response.Status="301 Moved Permanently" Response.AddHeader='Location','http://www.new-url.com/' %> Canonical Hostname Redirect (non-www to www):This code should be inserted into a global include file or any ASP script which is executed for every page on the site before the page output begins:
<%
If InStr(Request.ServerVariables("SERVER_NAME"),"www") = 0 Then
Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://www."
& Request.ServerVariables("HTTP_HOST")
& Request.ServerVariables("REQUEST_URI")
Response.End
End if
%>
ColdFusionSingle Page Redirect:
<cfheader statuscode="301" statustext="Moved permanently">
<cfheader name="Location" value="http://www.new-url.com/"> |
