We have a website at domain.com, which is also accessible via a CNAME entry for www.domain.com that points back to domain.com. We'd like all visitors to www.domain.com to be redirected to domain.com using a 301 redirect. What's the best way to implement this in asp.net mvc? In global.asax?
Asked
Active
Viewed 8,521 times
11
-
4The easiest way is to create another Website in IIS to handle the redirection. You wouldn't need to code--IIS redirection could deal with it automatically. – Mehrdad Afshari Feb 01 '10 at 11:02
-
1Indeed. IIS is the way to go. You don't really want to tie your application up with this sort of thing when IIS does it for free. IIS7 is your best bet here. – Dan Atkinson Feb 01 '10 at 11:43
-
1The problem here is that the site is in a farm sitting behind a load-balancer over which we have little control. The host resolves to the internal IP address of the server and the original hostname is repackaged in a header "x-forwarded-host". As far as I can see, this rules out using the IIS7 HTTP Redirect feature. – spender Feb 01 '10 at 16:55
-
you might want to take a look at this http://serverfault.com/questions/145777/whats-the-point-in-having-www-in-a-url – Cherian Feb 27 '11 at 15:16
1 Answers
22
I accept that doing this at application level is non-desirable as per the comments to the question.
Installing the HTTP Redirect feature in IIS7 is the best way to do this.
In our case, other constraints force us to do this at application level.
Here is the code that we use in global.asax to perform the redirect:
private static readonly Regex wwwRegex =
new Regex(@"www\.(?<mainDomain>.*)",
RegexOptions.Compiled
| RegexOptions.IgnoreCase
| RegexOptions.Singleline);
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string hostName = Request.Headers["x-forwarded-host"];
hostName = string.IsNullOrEmpty(hostName) ? Request.Url.Host : hostName;
Match match = wwwRegex.Match(hostName);
if (match.Success)
{
string mainDomain = match.Groups["mainDomain"].Value;
var builder=new UriBuilder(Request.Url)
{
Host = mainDomain
};
string redirectUrl = builder.Uri.ToString();
Response.Clear();
Response.StatusCode = 301;
Response.StatusDescription = "Moved Permanently";
Response.AddHeader("Location", redirectUrl);
Response.End();
}
}

spender
- 117,338
- 33
- 229
- 351
-
gives me : Invalid group name: Group names must begin with a word character – Liron Harel Feb 17 '13 at 13:37
-
2This has now been made easier using UrlRewrite that can be added to the site's web.config. Just wanted mention it here. http://stackoverflow.com/a/10193142 – galdin Oct 05 '14 at 19:00
-
which is best for SEO with `www` or without `www` because [this](http://stackoverflow.com/q/15951963/2218697) post says with ? – Shaiju T Dec 23 '16 at 15:24
-
1@stom I suggest you take that question to an appropriate forum. This isn't it. – spender Dec 23 '16 at 15:52