Conditional 301 Redirect

A conditional redirect is useful when subdomains must redirect to the content of a subfolder other than the document root. Typically, domain.com will display content placed within the document root (e.g. C:\inetpub\www\index.aspx); however, it is possible for a subdomain (e.g. sub.domain.com) to display the content of a sub-folder (e.g. C:\inetpub\www\other_content\index.html).

To implement a conditional 301 redirect, two elements must be present at the top of the default document (e.g. C:\inetpub\www\index.aspx): an if statement testing the incoming HTTP header and the 301 redirect.

Below are some examples of conditional 301 redirects in several common scripting languages:

ASP

if Request.ServerVariables("SERVER_NAME") = "sub.domain.com" then
      Call Response.Redirect("http://sub.domain.com/other_content/index.html")
end if

ASP .NET

private void Page_Load(object sender, System.EventArgs e)
{
If (Request.ServerVariables["SERVER_NAME"] == "sub.domain.com") then
    Response.Status = "301 Moved Permanently";
    Response.AddHeader("Location","http://sub.domain.com/other_content/index.html");
end if
}

PHP

$referer = $_SERVER['HTTP_HEADER'];
$domain = sub.domain.com
if(strpos($referer, $domain)!== FALSE) {
    header( "HTTP/1.1 301 Moved Permanently" );
    header( "Status: 301 Moved Permanently" );
    header( "Location: http://sub.domain.com/other_content/index.html" );
    exit(0);
}

.htaccess

RewriteEngine On
RewriteCond %{http_host} ^domain.com
RewriteRule ^(.*) http://sub.domain.com/other_content/index.html [R=301,L]

ColdFusion

<cfif (CGI.SERVER_NAME NEQ "domain.com")>
<cfheader statuscode="301" statustext="Moved permanently">
<cfheader name="Location" value="http://sub.domain.com/other_content/index.html">
</cfif>