1

I need to redirect my website when user enters URL without non www, and it should be redirect with www.

Example: abc.com to www.abc.com

And also i need to support subdomain url too.

Example: abc.xyz.com to www.abc.xyz.com

karthik
  • 33
  • 1
  • 4

2 Answers2

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>
Ahmet Kakıcı
  • 6,294
  • 4
  • 37
  • 49
1

You can also catch this in global, Applicaton_BeginRequest:

string url = HttpContext.Current.Request.RawUrl;

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

Edit: This question shows that 302 is returned by Response.Redirect.

As someone has answered there, Response.RedirectPermament can be used with .NET 4.0 and this will return 301.

Weird thing is. I use Response.Redirect on one of my sites in .NET 4.0 and it returns 301 just fine.

Community
  • 1
  • 1
DevDave
  • 6,700
  • 12
  • 65
  • 99
  • Downvoted as `Response.Redirect` doesn't do a 301 redirect so not great for search engines. – rtpHarry Jul 25 '13 at 12:26
  • strange, this returns 301 for me – DevDave Jul 25 '13 at 12:46
  • 301 is good, 302 is bad. I just checked the [documentation for response.redirect on .net 4.5](http://msdn.microsoft.com/en-us/library/a8wa7sdt%28v=vs.110%29.aspx) and it says it does 302. You are correct that about the `RedirectPermanent` in 4+ would do a search engine friendly 301 redirect. – rtpHarry Jul 25 '13 at 12:54
  • yeah, can't think why Response.Redirect returns 301 for me. – DevDave Jul 25 '13 at 13:03
  • Maybe you have an extension method in there somewhere? – rtpHarry Jul 25 '13 at 22:24
  • took off the -1 as the answer points it out now – rtpHarry Jul 25 '13 at 22:25
  • No extension just does a Response.Redirect and I have tested it and returns 301. Thanks though, will change it to Response.RedirectPermanent anyway. – DevDave Jul 26 '13 at 10:33