I am attempting to force the domain name to not use the 'www'. I want to redirect the user if attempted. I have seen very little on an MVC solution. Is there anyway to harness the routing built into MVC, or what the best solutions is.
Thanks
I am attempting to force the domain name to not use the 'www'. I want to redirect the user if attempted. I have seen very little on an MVC solution. Is there anyway to harness the routing built into MVC, or what the best solutions is.
Thanks
If you have control over the server, you should set up a virtual directory that accepts requests for "www.domain.com" and permanently redirects (301) them to "domain.com"
While this may be possible in ASP.NET MVC, it is not ASP's job to do this sort of redirecting.
On IIS:
On Apache:
<VirtualHost *:80>
ServerName www.domain.com
Redirect permanent / http://domain.com/
</VirtualHost>
Both the IIS and the Apache settings will preserve the URL stem.
Implemented as an ActionFilter as that is MVC-like, and more explicit.
public class RemoveWwwFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var req = filterContext.HttpContext.Request;
var res = filterContext.HttpContext.Response;
var host = req.Uri.Host.ToLower();
if (host.StartsWith("www.")) {
var builder = new UriBuilder(req.Url) {
Host = host.Substring(4);
};
res.Redirect(builder.Uri.ToString());
}
base.OnActionExecuting(filterContext);
}
}
Apply the ActionFilter to your controllers, or your base controller class if you have one.
For an introduction to Action Filters, see Understanding Action Filters on MSDN.
[RemoveWwwFilterAttribute]
public class MyBaseController : Controller
Although I believe John Gietzen's answer is the most elegant solution, I was unable to implement do to a shared hosting environment. Determined to find a non-application driven solution I found this blog post which shows a good alternative method for IIS7. Thankfully DiscountASP.NET's has the URL Rewrite module available through the IIS Manager tool.
Following this blog post on creating a rewrite rule any URL with www in the domain will do a permanent 301 redirect to the non-www site. All while preserving the full paths.
Thanks for everyone's input.