Asp.net MVC 301 www.domain.com重定向到domain.com [英] Asp.net mvc 301 redirect from www.domain.com to domain.com

查看:118
本文介绍了Asp.net MVC 301 www.domain.com重定向到domain.com的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们必须在domain.com一个网站,这也是通过一个CNAME条目www.domain.com指向回domain.com访问。我们希望所有访问者www.domain.com重定向使用301重定向到domain.com的。是什么在asp.net mvc的实现这一目标的最佳方式是什么?在Global.asax中?

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?

推荐答案

我承认在应用层面做的,这是不期望按照该意见的问题。

I accept that doing this at application level is non-desirable as per the comments to the question.

安装在HTTP重定向IIS7的特点是做到这一点的最好办法。

在我们的例子中,其他方面的限制迫使我们在应用层面做到这一点。

In our case, other constraints force us to do this at application level.

下面是我们在Global.asax的用于执行重定向的code:

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

这篇关于Asp.net MVC 301 www.domain.com重定向到domain.com的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆