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

查看:22
本文介绍了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> 

根据这篇文章

如何使用www"重定向不带www"的 URLURL 或反之亦然?

但我收到了 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 Moved Permanently.

This one will return 301 Moved Permanently.

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

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