example.com
to www.example.com
).Β
In ASP.NET, you can easily enforce this redirect using code in the Global.asax
file.
You're managing an ASP.NET Web Forms or MVC site.
You want to enforce a www-only version of your domain for SEO, branding, and SSL consistency.
You're not using a reverse proxy or external redirect rules (like in IIS or a CDN).
Global.asax.cs
Add the following code to the Application_BeginRequest
method:
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 request is missing βwwwβ.
β Skips redirects for localhost (useful during development).
β Redirects to the www version using a 302 redirect (or 301 if you prefer).
To enforce a permanent redirect for SEO:
Response.Redirect(builder.ToString(), true); // Temporary (302)
// Replace with:
Response.RedirectPermanent(builder.ToString()); // Permanent (301)
Ensure your SSL certificate covers both www and non-www domains (or use a wildcard certificate).
Only implement this redirect in one place (Global.asax or IIS or CDN) to avoid conflicts.
For larger websites or multi-domain setups, consider implementing this rule at the server level (IIS or load balancer)