Remove "www" from domain by doing 301 redirect

1

How do I redirect a www.dominio.com.br to dominio.com.br (without www)?

I'm using asp.net mvc .

    
asked by anonymous 03.01.2016 / 15:55

1 answer

1
  

Note: At first I thought it was a duplicate of How to redirect from non-www to www? but at I read that the question here is to remove the "www" and not add, in the other question I did not see examples of removing the "www" for this I am responding here.

I found two answers in SOen :

  • Editing web.config ( redirectType="Permanent" indicates permanent redirect that is 301):

    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Remove WWW prefix" >
                    <match url="(.*)" ignoreCase="true" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^www\.domain\.com" />
                    </conditions>
                    <action type="Redirect" url="http://domain.com/{R:1}" redirectType="Permanent" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
    

    If you prefer to add www, change to:

                <add input="{HTTP_HOST}" pattern="^domain\.com" /> 
            </conditions> 
            <action type="Redirect" url="http://www.domain.com/{R:1}" redirectType="Permanent" /> 
        </rule> 
    
  • Using the programming language, in this case an example with C #:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
       if (Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
       {
          UriBuilder builder = new UriBuilder(Request.Url);
          builder.Host = Request.Url.Host.Replace("www.","");
          Response.StatusCode = 301;
          Response.AddHeader("Location", builder.ToString());
          Response.End();
       }
    }
    

    If you prefer to add www, change to:

    UriBuilder builder = new UriBuilder(Request.Url);
    builder.Host = "www." + Request.Url.Host;
    
03.01.2016 / 17:00