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();
}
}