asp.net的MVC:如何将非WWW重定向到www,反之亦然 [英] asp.net mvc: How to redirect a non www to www and vice versa

查看:108
本文介绍了asp.net的MVC:如何将非WWW重定向到www,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想所有的WWW流量重定向到非www交通

I would like to redirect all www traffic to non-www traffic

我已经复制到我的web.config这

i have copied this into my web.config

<system.webServer> / <rewrite> / <rules> 

<rule name="Remove WWW prefix" > 
<match url="(.*)" ignoreCase="true" /> 
<conditions> 
<add input="{HTTP_HOST}" pattern="^www\.domain\.com" /> 
</conditions> 
<action type="Redirect" url="http://domain.com/{R:1}" 
    redirectType="Permanent" /> 
</rule> 

根据该职位

<一个href=\"http://stackoverflow.com/questions/521804/how-to-redirect-with-www-urls-to-without-www-urls-or-vice-versa/521811#521811\">http://stackoverflow.com/questions/521804/how-to-redirect-with-www-urls-to-without-www-urls-or-vice-versa/521811#521811

但我得到了500内部服务器错误。

but I got a 500 internal server error.

推荐答案

您可以考虑不同的方法:

You might consider a different approach:

protected void Application_BeginRequest (object sender, EventArgs e)
{
   if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
   {
      UriBuilder builder = new UriBuilder (Request.Url);
      builder.Host = "www." + Request.Url.Host;
      Response.Redirect (builder.ToString (), true);
   }
}

然而,这将做302重定向所以小调整建议:

This will however do a 302 redirect so a little tweak is recommended:

protected void Application_BeginRequest (object sender, EventArgs e)
{
   if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
   {
      UriBuilder builder = new UriBuilder (Request.Url);
      builder.Host = "www." + Request.Url.Host;
      Response.StatusCode = 301;
      Response.AddHeader ("Location", builder.ToString ());
      Response.End ();
   }
}

这人会返回301永久移动。

This one will return 301 Moved Permanently.

这篇关于asp.net的MVC:如何将非WWW重定向到www,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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