.NET: Redirect Non-WWW Requests to WWW Requests in ASP/MVC

5/21/2015 9:32:33 PM

For SEO purposes, you may want to redirect all requests to WWW. The following codes use the Global.asax Application_BeginRequest() to capture the request and redirect.

protected void Application_BeginRequest()
{						
	//redirect to www
	string url = HttpContext.Current.Request.Url.ToString();                        
	bool redirectToWWW = false;

	//dont redirect to www on localhost
	//could also set up a appsetting to control when to force redirect
	redirectToWWW = !url.Contains("localhost");

	if (redirectToWWW)
	{						
		string scheme = HttpContext.Current.Request.Url.Scheme;
		if (!url.StartsWith(scheme + "://www."))
		{
			string newUrl = url.Replace(scheme + "://", scheme + "://www.");
			Response.Redirect(newUrl);
		}
	}
}