0

I need to redirect user to a secure connection with www included in url my code is working for https connection but if user types https mysite.com. it should always redirect user to https www.mysite.com below is my code

 if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
    {
        Response.AddHeader("Strict-Transport-Security", "max-age=31536000");
        Response.Status = "301 Moved Permanently";
        Response.RedirectPermanent("https www.mysite.com" + HttpContext.Current.Request.RawUrl);
    }
    if (Request.Url.Host.ToString().StartsWith("www", StringComparison.OrdinalIgnoreCase).Equals(false))
    {
        Response.AddHeader("Strict-Transport-Security", "max-age=31536000");
        Response.Status = "301 Moved Permanently";
        Response.RedirectPermanent("https www.mysite.com" + HttpContext.Current.Request.RawUrl);
    }
Ali Kazmi
  • 45
  • 1
  • 8
  • Better use IIS rewrite: https://stackoverflow.com/questions/42401506/web-config-url-rewrite-force-www-prefix-and-https – VDWWD May 17 '20 at 21:49

1 Answers1

0

thanks for advice VDWWD

<system.webServer>
<urlCompression doDynamicCompression="true" />
<rewrite>
  <rules>
    <clear />
    <rule name="RedirectNonWwwToWww" 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>
    <rule name="Redirect to https" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
    </rule>
    <rule name="LowercaseAllUrls" stopProcessing="true">
      <match url=".*[A-Z].*" ignoreCase="false" />
      <action type="Redirect" url="{ToLower:{R:0}}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>
    <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
    </staticContent>

Ali Kazmi
  • 45
  • 1
  • 8