what is the best way to redirect site users who do not enter the www in a domain name to actually get the www site.
IE: I goto Google.com and I am redirected to www.Google.com
what is the best way to redirect site users who do not enter the www in a domain name to actually get the www site.
IE: I goto Google.com and I am redirected to www.Google.com
If this is to be handed correctly it should be done as an alias on the http server, not in your code...imo.
So when the server is contacted without the www, it should just redirect it to the correct URL.
This is best handled via an A record (or CNAME record) on the DNS server that manages your domain. You can handle this in code but it really isn't the proper place for it.
The most common way of dealing with this is to do a redirect when the URL isn't what you expected. Typically this is done using some sort of mod_rewrite module.
In ASP.NET MVC, you would have to catch the incoming request as early as you can in the request lifecycle, check the URL and then redirect (response code 301 or 302) to the correct URL if need be.
I found sample code from this blog post: Canonical urls With ASP.NET MVC. It demonstrates one way of accomplishing this:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (Request.Url.Authority.StartsWith("www"))
return;
string url = (Request.Url.Scheme
+ "://www."
+ HttpContext.Current.Request.Url.Authority
+ HttpContext.Current.Request.Url.AbsolutePath
);
Response.Clear();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", url);
Response.End();
}
For those of us doing things with Mono and Apache or using one of the mod_rewrite extensions to IIS, here is a mod_rewrite example:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com$1 [R=301,L]
Following these suggestions about having an A record or CNAME only allow people to access the site from both domains, but it reduces your Google Juice because you have the same content at two different URLs.
Should not ignore the 301 redirections. There is a nice post written by shahed khan to deal with that kind of situation. http://dotnetusergroup.com/blogs/shahedkhan/archive/2009/05/18/10229.aspx
If you're using the Microsoft IIS URL Rewrite Module then the following entry in your web.config will keep your domain consistent.
<rewrite>
<rules>
<rule name="Consistent Domain" stopProcessing="true">
<match url="^(.*)$" ignoreCase="false" />
<conditions>
<add input="{HTTP_HOST}" pattern="^mediapopinc.com$" />
</conditions>
<action type="Redirect" redirectType="Permanent" url="http://www.mediapopinc.com/{R:1}" />
</rule>
</rules>
</rewrite>