ASP.net MVC站点:将所有“非WWW”请求重定向到WWW

问题描述:

最近我将一个ASP.net站点迁移到ASP.net MVC站点。此前有两个主机标题mydomain.com,另一个是www.mydomain.com。我的搜索引擎优化说,你应该只使用一个网址“www.domain.com”搜索引擎优化的优势。ASP.net MVC站点:将所有“非WWW”请求重定向到WWW

我正在寻找一个选项来做301永久重定向所有mydomain.com请求www.mydomain.com。

该网站在IIS6主办,开发ASP.net MVC 4

不幸的是,URL重写模块不能与IIS6(仅限IIS7或更高版本)一起使用。你有没有考虑过创建你自己的HttpModule,像这样?

IIS 6 how to redirect from http://example.com/* to http://www.example.com/*

或者你可能使用像其中的一个第三方的解决方案:

http://iirf.codeplex.com/

http://www.urlrewriting.net/149/en/home.html

http://www.isapirewrite.com/

http://urlrewriter.net/

你可以从你的web.config文件

<system.webServer> 
    <rewrite> 
     <rules> 
      <rule name="Redirect to WWW" stopProcessing="true"> 
      <match url=".*" /> 
      <conditions> 
       <add input="{HTTP_HOST}" pattern="^example.com$" /> 
      </conditions> 
      <action type="Redirect" url="http://www.example.com/{R:0}" 
       redirectType="Permanent" /> 
      </rule> 
     </rules> 
    </rewrite> 
</system.webServer> 
+0

这是一个很好的答案,@汤米;不是一线C#在视线。 – 2013-04-11 15:43:19

+0

为了使用URL重写模块,您必须使用IIS7或更高版本。如果你至少有IIS7,这是一条路,但它不适用于IIS6。 – Craig 2013-04-13 22:35:18

+0

@Tommy - 使用IIS7 URL重写模块还是更好?如果您有能力使用两者,webApp中的网络路由功能是否可以做重定向?或者(第三个选项)我是否应该对URL和URL重写模块中的反向代理都做出响应并保持URL? ...尽管最后的第三个选项对于SEO来说并不理想,但我会这么想。 – johntrepreneur 2013-07-22 21:41:16

你可以在IIS中使用的配置或URL重写做到这一点,但我发现最好的方法就是把在Application_BeginRequest()一些代码在你global.asax.cs这样的:

var HOST = "www.mydomain.com"; 

if (!Request.ServerVariables[ "HTTP_HOST" ].Equals(
    HOST, 
    StringComparison.InvariantCultureIgnoreCase) 
) 
{ 
    Response.RedirectPermanent(
    (HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://") 
    + HOST 
    + HttpContext.Current.Request.RawUrl); 
} 

因为你在代码实现这一点,你可以在每个请求的基础上拥有您需要的任何逻辑。

+0

我在配置中的所有方面尝试规则,但在IIS 7中没有成功,但此解决方案对我有用。非常感谢。 – CrazyDev 2016-12-20 07:45:02

(IIS 7或更高的要求)

http://www.codeproject.com/Articles/87759/Redirecting-to-WWW-on-ASP-NET-and-IIS

(以上述方案类似,但不要求你添加你自己的域名。)

<configuration> 
    <system.webServer> 
     <rewrite> 
      <rules> 
       <clear /> 
       <rule name="WWW Rewrite" enabled="true"> 
        <match url="(.*)" /> 
        <conditions> 
         <add input="{HTTP_HOST}" negate="true" 
          pattern="^www\.([.a-zA-Z0-9]+)$" /> 
        </conditions> 
        <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" 
         appendQueryString="true" redirectType="Permanent" /> 
       </rule> 
      </rules> 
     </rewrite> 
    </system.webServer> 
</configuration> 

请注意,您最可能会在标签下方看到一条标签无效的消息。我收到了这条消息,但事实上,它工作得很好。

如果你想在智能感知工作,你可以尝试在这里此更新...

http://ruslany.net/2009/08/visual-studio-xml-intellisense-for-url-rewrite-1-1/

有关httpRedirect的更多信息可以在这里找到...

http://www.iis.net/configreference/system.webserver/httpredirect