开发者

Asp.net mvc 301 redirect from www.domain.com to domain.com

开发者 https://www.devze.com 2022-12-19 06:18 出处:网络
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

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.asa开发者_如何学编程x?


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

精彩评论

暂无评论...
验证码 换一张
取 消