ASP.NET MVC:如何将非www重定向到www,反之亦然

49

我想要将所有的www流量重定向到非www流量。

我已将此复制到我的web.config中。

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

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

根据这篇文章

如何将带有“www”的URL重定向到不带“www”的URL或反之亦然?

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

9个回答

84
你可以考虑采用不同的方法:
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重定向,因此建议进行一些微调:

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永久重定向。


1
这种方法在MVC中可行吗?你的方式是我在Web Forms中所做的,但我认为MVC Routing Framework的处理方式不同。 - Chase Florell
1
我采用了非常相似的方法。请参见https://dev59.com/l3I95IYBdhLWcg3wvgl9 - spender
3
自.NET 4.0以来,有Response.ResponsePermanent方法,该方法使代码比手动设置标头更简单。 - jakubka
3
我认为你实际上是想输入Response.RedirectPermanent。不过你的链接是正确的。 - Perry
这个解决方案是基于代码的,比依赖于HTTP重定向模块安装在服务器上的web.config选项实现起来要快得多,这意味着没有IIS停机时间。非常有用,谢谢。 - Ian Jowett
显示剩余4条评论

14

如果您直接复制了它,那么您的web.config中存在不正确的标记。

您需要:

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

这行代码的含义是

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

这里是说你需要将配置放置在web.Config文件中的那个位置。 <system.webServer>web.Config文件中的一个configSections

确保您先安装了IIS7的URL Rewrite模块

上面的页面讨论了将HTTP重定向到HTTPS,但是这个概念仍然适用于WWW到非WWW

此外,这里有一些详细信息介绍了它们如何共同使用。


好的,我已经完成了这个操作,但它显示“<rewrite>”不是一个有效的标签。 - Luke101
我编辑了我的回答。我仍在寻找如何使Visual Studio不对您发出警告,但它应该适用于IIS7。 - Chase Florell
@ChaseFlorell - 如果你能够同时使用两种方法,那么在webApp内部使用.Net路由功能还是使用IIS7 URL Rewrite模块进行重定向更好?或者(第三种选择)我应该同时响应这两个URL,并使用URL Rewrite模块中的反向代理来维护这两个URL?尽管最后一个第三种选择对于SEO来说不是理想的选择。 - johntrepreneur

8
    **For a www to a non www Thanks @developerart**

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 = Request.Url.Host.Replace("www.","");
            Response.StatusCode = 301;
            Response.AddHeader("Location", builder.ToString());
            Response.End();
        }
    }

5
protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (!this.Request.Url.Host.StartsWith("www") && !this.Request.Url.IsLoopback)
    {
        var url = new UriBuilder(this.Request.Url);
        url.Host = "www." + this.Request.Url.Host;
        this.Response.RedirectPermanent(url.ToString(), endResponse: true);
    }
}

4

您可以使用https和www重定向。(您需要更改"example")

<system.webServer>
  <!-- For force ssl and www -->
  <rewrite>
    <rules>
      <!-- For force ssl -->
      <rule name="http to https" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
          <add input="{HTTPS}" pattern="^OFF$" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
      </rule>
      <!-- For force ssl -->
      <!-- For force www -->
      <rule name="redirect to www" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
          <add input="{HTTP_HOST}"  pattern="^example\.com$" />
        </conditions>
        <action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" redirectType="Permanent" />
      </rule>
      <!-- For force www -->
    </rules>
  </rewrite>
  <!-- For force ssl and www -->
</system.webServer>

3

在用户151323的回答的基础上,这里是完整的答案,适用于希望防止用户从azurewebsites.net子域名访问网站的Azure用户(将此代码放入您的 Global.asax 中的主类中(对于MVC用户是MvcApplication)):

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.Url.Host.StartsWith("YourSite.azurewebsites") && !Request.Url.IsLoopback)
        {
            Response.StatusCode = 301;
            Response.AddHeader("Location", "www.example.com");
            Response.End();

            return;
        }

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

1
我知道这个帖子古老且已经有过多次回答。但是,将大家的global.asax建议与本地/远程检查结合起来可能会很有用。这样,在使用IIS Express进行开发时,您的网站将不会尝试重定向到'www'子域名。
类似以下方式:

如下:

protected void Application_BeginRequest(
        object sender,
        EventArgs e)
    {
        if (!Request.IsLocal)
        {
            // Do your check for naked domain here and do permanent redirect
        }
    }

0

0

您可以通过编写规则在IIS中实现将非www重定向到www的服务器级别。

这个规则是有效的,但请注意,只有在您的IIS服务器上安装了URL Rewrite时,此规则才能起作用。如果您的IIS服务器上没有安装URL Rewrite,则此规则将无法工作。

为了在您的服务器上安装URL Rewrite,请访问官方网站link并下载扩展程序进行安装。之后重新启动IIS服务器即可。

URL Rewrite扩展官方网站链接:https://www.iis.net/downloads/microsoft/url-rewrite

<rewrite>
            <rules>
                <rule name="Redirect example.com to http://www.example.com HTTP" patternSyntax="ECMAScript" stopProcessing="true">
                    <match url=".*"></match>
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^example.com$"></add>
                        <add input="{HTTPS}" pattern="off"></add>
                    </conditions>
                    <action type="Redirect" url="http://www.example.com/{R:0}" redirectType="Permanent" appendQueryString="true"></action>
                </rule>
            </rules>
        </rewrite>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接