When we build SEO friendly website we always care of how to handle sub-domain policy with www and non www sub-domains. Google and most of SEO specialist recommended to use of one sub-domain policy (www or non www) for better indexing. basic concept is to use of this avoid duplicate content on same domain. Google badly hurting to indexing when if it saw a duplicate content. So it’s good idea to have a sub-domain policy.
OK, lets say we choose to use non www for our sub-domain policy. the next problem is
what about other URLs with www sub-domain?
that’s why we forcedly permanent redirect to the non www URLs
How we achieve this with asp.net way?
Here is the simple approach with code I use own HttpModule to handle www URLs.Here we go
we use regex to match URLs with www
private static readonly Regex LinkRegex = new Regex(
"(http|https)://www\\.", RegexOptions.IgnoreCase | RegexOptions.Compiled);
then implementation with IHttpModule Interface like this
public void Init(HttpApplication context)
{
context.BeginRequest += OnBeginRequest;
}
private static void OnBeginRequest(object sender, EventArgs e)
{
var context = ((HttpApplication)sender).Context;
var url = context.Request.Url.ToString();if (!context.Request.PhysicalPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)) return;if (!url.Contains("://www.")) return;if (!LinkRegex.IsMatch(url))return;
url = LinkRegex.Replace(url, "$1://");if (url.EndsWith("default.aspx", StringComparison.OrdinalIgnoreCase))
url = url.ToLowerInvariant().Replace("default.aspx", string.Empty);
context.Response.Clear();
context.Response.StatusCode = 301;
context.Response.AppendHeader("location", url);
context.Response.End();
}
Important !! this is when you define this module on web.config file this module should be the first defined one, so will fire before any other modules.
Hope this helped you to put some smile on you code editor. :)