If you want users to always access your website via www.yourdomain.com instead of just yourdomain.com, you can enforce this rule using the following ASP.NET Global.asax code:
protected void Application_BeginRequest(object sender, EventArgs e)
{
// Ensure the request starts with "www" and is not localhost (for development)
if (!Request.Url.Host.StartsWith("www") && !Request.Url.IsLoopback)
{
// Redirect to the www version
UriBuilder builder = new UriBuilder(Request.Url);
builder.Host = "www." + Request.Url.Host;
Response.Redirect(builder.ToString(), true);
}
}
✅ Runs at the beginning of every request
✅ Checks if the URL starts with "www"
✅ Excludes localhost for local development
✅ Redirects to www.yourdomain.com for consistency