Domanda

I am trying to redirect non-www website to www but when i add redirect rule in my web.config or in my Global.asax it shows that page isn't redirecting properly. Redirect rule in web.config

    <rewrite>
      <rules>
        <rule name="CanonicalHostNameRule" enabled="true">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
            <add input="{HTTP_HOST}" pattern="testdomain\.com$" />
            <add input="{HTTP_HOST}" pattern="^www\.testdomain\.com$" negate="true" />
          </conditions>
          <action type="Redirect" url="http://www.testdomain.com/{R:1}" />
        </rule>
      </rules>
    </rewrite>

i have also tried this from Global.asax inside Application_BeginRequest NOTE: i am trying one of these things at a time.

if(HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://testdomain.com"))
{
    HttpContext.Current.Response.Status = "301 Moved Permanently";
    HttpContext.Current.Response.AddHeader("Location",
    Request.Url.ToString().ToLower().Replace("http://testdomain.com", "http://www.testdomain.com"));
}

My Default.aspx and Default.aspx.cs page has no code in it.. Any idea guys where the actual problem could be.

È stato utile?

Soluzione

add this code this code under <system.webServer> section

<rewrite>
<rule name="Redirect to www">
  <match url=".*" />
  <conditions logicalGrouping="MatchAny">
    <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" negate="true" />
  </conditions>
  <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" redirectType="Permanent"/>
</rule>
</rewrite>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top