Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC site : Redirect all "non WWW" request to WWW

Recently I migrated an ASP.net site to ASP.net MVC site. Earlier there were two host headers one mydomain.com and another is www.mydomain.com. My SEO says you should use only one url "www.domain.com" for SEO advantage.

I am looking for an option to do 301 permanent redirect all mydomain.com request to www.mydomain.com.

The site is hosted in IIS6 and developed in ASP.net MVC 4.

like image 882
Karthick Avatar asked Apr 11 '13 14:04

Karthick


People also ask

What is redirect to route in MVC?

RedirectToRoute(String, RouteValueDictionary)Redirects to the specified route using the route name and route dictionary.


2 Answers

You can do this from your web.config file

<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>
like image 187
Tommy Avatar answered Nov 06 '22 03:11

Tommy


You could use config or Url Rewriter in IIS, but the best method I've found is just to put some code in Application_BeginRequest() in your global.asax.cs like this:

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

Because you're doing this in code, you can have whatever logic you need on a per-request basis.

like image 5
Nick Butler Avatar answered Nov 06 '22 03:11

Nick Butler