There was a problem loading the comments.

How to Force WWW in Your ASP.NET Website Using Global.asax

Support Portal  »  Knowledgebase  »  Viewing Article

  Print
To ensure consistency and avoid duplicate content issues, it's best to redirect all non-www traffic to theΒ www version of your domain (e.g., from example.com to www.example.com).

Β 

In ASP.NET, you can easily enforce this redirect using code in the Global.asax file.


βœ… When to Use This

  • 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).


πŸ›  Code to Force WWW in 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);
    }
}

πŸ’‘ How It Works

  • βœ… 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).


πŸ” Optional: Make Redirect Permanent (301)

To enforce a permanent redirect for SEO:

Response.Redirect(builder.ToString(), true); // Temporary (302)
// Replace with:
Response.RedirectPermanent(builder.ToString()); // Permanent (301)

🧠 Best Practices

  • 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)



Share via
Did you find this article useful?  

Related Articles

Tags

© Softsys Hosting