从非www重定向到www并且还支持子域

时间:2013-07-25 11:04:45

标签: asp.net c#-4.0

我需要在用户输入不带非www的网址时重定向我的网站,并且应该使用www重定向。

实施例: abc.com到www.abc.com

我也需要支持子域名。

实施例: abc.xyz.com到www.abc.xyz.com

2 个答案:

答案 0 :(得分:1)

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <rewrite>
      <rules>
        <rule name="non-www to www" enabled="true" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^[^\.]+\.[^\.]+$" />
          </conditions>
          <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

答案 1 :(得分:1)

您还可以在全局Applicaton_BeginRequest

中捕捉到这一点
string url = HttpContext.Current.Request.RawUrl;

    if (!url.StartsWith("www.")) {
      Response.Redirect("www." + url);
    }

修改This question显示Response.Redirect返回302。

当有人在那里回答时,Response.RedirectPermament可以与.NET 4.0一起使用,这将返回301。

奇怪的是。我在Response.Redirect的某个网站上使用了.NET 4.0,它返回301就好了。

相关问题