2013-04-11 134 views
5

最近我將一個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

回答

18

你可以從你的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

5

你可以在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

0

(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