Most websites needs a policy for handling the www sub domain because of SEO. It doesn’t matter if you redirect all requests coming from http://www.example.com to http://example.com or the other way around. The important thing is that you do one of them. Otherwise search engines will punish you for duplicate content.
This is the bit that handles the incoming request and either removes or enforces the www sub domain based on a web.config appSetting.
/// <summary>
/// Handles the BeginRequest event of the context control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void context_BeginRequest(object sender, EventArgs e)
{
string rule = ConfigurationManager.AppSettings.Get("WwwRule");
HttpContext context = (sender as HttpApplication).Context;
if (context.Request.HttpMethod != "GET" || context.Request.IsLocal)
return;
if (context.Request.PhysicalPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase))
{
string url = context.Request.Url.ToString();
if (url.Contains("://www.") && rule == "remove")
RemoveWww(context);
if (!url.Contains("://www.") && rule == "add")
AddWww(context);
}
}
/// <summary>
/// Adds the www subdomain to the request and redirects.
/// </summary>
private static void AddWww(HttpContext context)
{
string url = context.Request.Url.ToString().Replace("://", "://www.");
PermanentRedirect(url, context);
}
private static readonly Regex _Regex = new Regex("(http|https)://www\\.", RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>
/// Removes the www subdomain from the request and redirects.
/// </summary>
private static void RemoveWww(HttpContext context)
{
string url = context.Request.Url.ToString();
if (_Regex.IsMatch(url))
{
url = _Regex.Replace(url, "$1://");
PermanentRedirect(url, context);
}
}
/// <summary>
/// Sends permanent redirection headers (301)
/// </summary>
private static void PermanentRedirect(string url, HttpContext context)
{
context.Response.Clear();
context.Response.StatusCode = 301;
context.Response.AppendHeader("location", url);
context.Response.End();
}