Today I was asked if we could set up a 301 Redirect for all non “www” request. For example if someone requested http://robbihun.com/page/about-me.aspx it would automatically do a 301 (permanent) redirect to http://www.robbihun.com/page/about-me.aspx thus making all existing links (and SEO links) work without issue.
Basically all you have to do is check the requested url, check for the existance of the www. and if it is not present, set the HTTP Headers to do a 301 redirect to the same page to the www request.
I added the following to the master page – its not my favorite code ever, but it was quick to write and implement… and most importantly, works.
protected void Page_Load(object sender, EventArgs e)
{
string requestPath = GetApplicationPath().ToLowerInvariant();
string redirectPath = "~";
if (!requestPath.Contains("www."))
{
if (requestPath.Contains("http://"))
{
redirectPath = reqPath.Substring(reqPath.IndexOf('/', 6));
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", "http://www.domain.com" + redirectPath);
}
else
{
redirectPath = requestPath.Substring(reqPath.IndexOf('/'));
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", "http://www.domain.com" + redirectPath);
}
}
}
public string GetApplicationPath()
{
string applicationPath = "";
if (this.Page.Request.Url != null)
applicationPath = this.Page.Request.Url.AbsoluteUri;
return applicationPath;
}
ASP.NET, General
redirect, asp.net