How to redirect from non-www to www?

Asked

Viewed 961 times

5

I want my website visitors to always access with www.

I want to somehow redirect in case the user tries to enter without www or Ubdomain. If you try to access exemplo.com I want to redirect to www.exemplo.com.

How can I do that?

  • 1

    Interesting! Just to complement there is a site that promotes the removal of www. Do a test: http://no-www.org/verify.php?u=SEUDOMINIO.COM&retest=1 Class A Domains (Accept both with WWW and without WWW). Class B domains (Redirect WWW to WWW-free). C-Class domains (Reject WWW and only accept without - not recommended)

2 answers

4


You can use the IIS URL Rewrite. To use on a server just download and install. Shared hosts usually include this module.

With this module installed just configure rules.

To redirect permanently (Redirect 301) from não-www for www, you can include this rule by setting the domain appropriately:

<system.webServer>
<rewrite>
  <rules>
   <rule name="Canonical" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^([a-z]+[.]com)$" />
      </conditions>
      <action type="Redirect" url="http://www.{C:0}/{R:0}" redirectType="Permanent" />
    </rule>
</rewrite>

If for some reason you cannot use the Rewrite URL, you can do it by code. No Global.asax.cs add

protected void Application_BeginRequest(object sender, EventArgs ev)
{
    if (!Request.Url.Host.Equals("example.com", StringComparison.InvariantCultureIgnoreCase))
    {
        Response.Clear();
        Response.AddHeader("Location", 
            String.Format("{0}://www.{1}{2}", Request.Url.Scheme, Request.Url.Host, Request.Url.PathAndQuery)
            );
        Response.StatusCode = 301;
        Response.End();
    }
}

There are advantages to using the www. You may have subdominios cookieless, for example static.exemplo.com. And in this domain you can display images that will be downloaded without the need to download cookies. To more information see this explanation. Think about it.


If you want to redirect from www for não-www (cokieless not important for you), you can configure IIS Rewrite with:

<system.webServer>
<rewrite>
  <rules>
    <rule name="Canonical" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^www[.](.+)" />
      </conditions>
      <action type="Redirect" url="http://{C:1}/{R:0}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>

And if you cannot use this module and need to do it by code, add to Global.asax.cs

protected void Application_BeginRequest(object sender, EventArgs ev)
{
    if (Request.Url.Host.StartsWith("www", StringComparison.InvariantCultureIgnoreCase))
    {
        Response.Clear();
        Response.AddHeader("Location", 
            String.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Host.Substring(4), Request.Url.PathAndQuery)
            );
        Response.StatusCode = 301;
        Response.End();
    }
}

4

One way to promote this is to take advantage of the modules of ASP.Net. You can create a module that will enter the ASP.Net execution pipeline and intercept the "www". For this just create a class that inherits the interface IHttpModule, and add a new line to your Web.Config.

This way you keep your Global.asax clean, and you don’t use the Web.Config to instruct your browser to do Redirects.

Class to create redirect module

public class RemoveWWW : IHttpModule
{
    public void Dispose(){}

    // Expressão Regular para identificar o www
    private static Regex regex = new Regex("(http|https)://www\\.", RegexOptions.IgnoreCase | RegexOptions.Compiled);

    public void Init(HttpApplication context)
    {
        // Intercepta o Begin Request
        context.BeginRequest += new EventHandler(BeginRequestHandler);
    }
    void BeginRequestHandler(object sender, EventArgs e)
    {
        HttpApplication application = sender as HttpApplication;
        Uri url = application.Context.Request.Url;
        bool contemWWW = regex.IsMatch(url.ToString());

        if (contemWWW)
        {
            // Esse replace é importante para manter o protocolo HTTP ou HTTPS
            string novaUrl = regex.Replace(url.ToString(), String.Format("{0}://", url.Scheme));

            // Redirect 302 ou 301 não fazem diferença para o Google, pois ele não faz distinção entre www.example.com e example.com
            application.Context.Response.Redirect(novaUrl);
        }
    }
}

Then the simplest part, add the module on the Web.Config

<system.web>
  <httpModules>
    <add name="RemoveWWW" type="NAMESPACE_DO_PROJETO.RemoveWWW, NomeDoAssembly"/>
  <httpModules>
<system.web>

You can compile into a separate DLL and reference in your project, reusing the same solution in other projects, just adding the module.

The main reason to avoid using Web.Config for this is maintenance and support. Including redirect rules on the web.Config opens up a range for customers to edit wrongly, increasing technical support cost. And if in a given scenario you want to disable the module it’s as simple as removing the line from the Web.Config, which would require extra work on Global.asax

One positive point for modules is code reusability. There is an article that gives some more ideas on how to use Http Modules for other things.

  • This does not answer the question as it is doing the opposite: Removing www from the url. @AP wanted to add www if the user did not have.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.