How to redirect from non-www to www?

6

I want visitors to my site to always access with www .

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

How can I do this?

    
asked by BrunoLM 11.12.2013 в 23:17

2 answers

5

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

With this module installed just set up rules.

To permanently redirect (Redirect 301) from não-www to www , you can include this rule by configuring 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 can not 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 www . You can have cookieless subdomains, for example static.exemplo.com . And in this field you can view images that are downloaded without the need to download cookies. For more information see this explanation . Think about it .

If you want to redirect from www to não-www ( cokieless is not important to 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 can not use this module and need to do it by code, add it 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();
    }
}
    
11.12.2013 / 23:17
4

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

This way you keep your Global.asax clean, and do not use Web.Config to instruct the browser to make redirects.

Class to create the 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);
        }
    }
}

After the simplest part, add the module in 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 refer to your project, reusing the same solution in other projects, just by adding the module.

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

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

    
12.12.2013 в 06:37