redirect http page to https in every browser

Hi,

I am using following code to redirect my aspx http page to https page.

The following code works fine in chrome, opera, firefox but fails in internet explorer.



My code:

<script type="text/javascript">
        window.location = window.location.href.replace(/^http:/, 'https:');

      </script>




------------------
in web.config

<rewrite>
            <rules>
                <clear />
                <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>
            </rules>
        </rewrite>

------------------------

 <httpCookies httpOnlyCookies="true" requireSSL="true" />


---------------------------

<add key="HttpsServer" value="prod"/>

in global.asax

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (ConfigurationManager.AppSettings["HttpsServer"].ToString() == "prod")
                //if (ConfigurationManager.AppSettings["HttpsServer"].ToString() == "stage")
                {
                    if (!HttpContext.Current.Request.IsSecureConnection)
                    {
                        if (!Request.Url.GetLeftPart(UriPartial.Authority).Contains("www"))
                        {
                            HttpContext.Current.Response.Redirect(
                                Request.Url.GetLeftPart(UriPartial.Authority).Replace("http://", "https://www."), true);
                        }
                        else
                        {
                            HttpContext.Current.Response.Redirect(
                                Request.Url.GetLeftPart(UriPartial.Authority).Replace("http://", "https://"), true);
                        }
                    }
                }
        }

Open in new window

--------------------------


thanks,
dinesh.
Dinesh KumarAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sammySeltzerCommented:
Hi,

Normally, we would do this in a non code way using our barracuda network.

Since you want to go the code route, then try this:

if (!Request.IsLocal && !Request.IsSecureConnection)
{
    string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
    Response.Redirect(redirectUrl, false);
    HttpContext.ApplicationInstance.CompleteRequest();
}

Open in new window


Add that piece of code to your page_load() event in your default page.
Steve BinkCommented:
The better way is to use IIS URL Rewrite.  This redirects the page at the server level.
btanExec ConsultantCommented:
Consider the Javascript to be replaced with
<script language="JavaScript">
<!-- begin hide

function ReDirectHttps()
{
var oldURL = window.location.hostname + window.location.pathname;
var newURL = "https://" + oldURL;
window.location = newURL;
}
ReDirectHttps();

// end hide -->
</script>

Open in new window

IIS URL Rewrite Module is available for IIS 7 and higher only. in web.config, needed
<rules>
        <rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAny">
          <add input="{SERVER_PORT_SECURE}" pattern="^1$" />
          <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/OWA/" redirectType="Permanent" />
        </rule>
</rules>

Open in new window

(Method 1) http://blogs.msdn.com/b/kaushal/archive/2013/05/23/http-to-https-redirects-on-iis-7-x-and-higher.aspx

For the checking of IsSecureConnection checks, probably to go simple first to see if it works for browsers
if (!Request.IsLocal && !Request.IsSecureConnection)
{
    string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
    Response.Redirect(redirectUrl, false);
    HttpContext.ApplicationInstance.CompleteRequest();
}

Open in new window

There is mention for the recommended pattern to terminate the request according to the framework documentation
When you use this method in a page handler to terminate a request for one page and start a new request for another page, set endResponse to false and then call the CompleteRequest method.
https://msdn.microsoft.com/en-us/library/a8wa7sdt(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Dinesh KumarAuthor Commented:
Please find the attachment and I also tried following
if (!Request.IsSecureConnection)
                {
                    string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
                    Response.Redirect(redirectUrl);
                    //HttpContext.Current.ApplicationInstance.CompleteRequest();
                }

Open in new window


Not sure, why in IE9 set as default ( windows 7) the url does not change to https even I set all SSL and TSL in internet options to true.
After-Redirection-Not-Show-in-IE.PNG
btanExec ConsultantCommented:
Maybe also check this "Do not save encrypted pages to disk" under Tools >Options >Advanced, is unchecked. By default, it should be unchecked already but checked for server build.
However, the option is occasionally set by Group Policy as an attack-surface-reduction measure, although the side-effects of doing so can be pretty dire. The problem is that this option makes SSL-delivered downloads uncacheable by default, and that can lead to the dreaded “Internet Explorer cannot download” dialog.
re-try by closing browser and restart it again.
Ref - http://blogs.msdn.com/b/ieinternals/archive/2010/04/21/internet-explorer-may-bypass-cache-for-cross-domain-https-content.aspx

In similar context, some shared the IE required an established http connection to be fully close if there is any redirected to https connection done. This is due to IE being "smart" to reuse existing http channel for https and out of context - ignorant of the new redirect. This can lead to potential error. So response header require explicit connection closure which i supposed it is under the IsSecureConnection()
e.g.  System.Web.HttpContext.Current.Response.AddHeader("Connection", "close");

See this (in fact it is not recommended for redirect unless you do a perm 301)
protected void Application_BeginRequest(Object sender, EventArgs e)
{
  switch (Request.Url.Scheme)
  {
    case "https":
      Response.AddHeader("Strict-Transport-Security", "max-age=300");
      break;
    case "http":
      var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
      Response.Status = "301 Moved Permanently";
      Response.AddHeader("Location", path);
      break;
  }
}
http://www.troyhunt.com/2011/11/owasp-top-10-for-net-developers-part-9.html
This also req browser to support HSTS. But the idea is under e.g. case "http"
Dinesh KumarAuthor Commented:
The above code also did  not work.. and surprisingly other sites like google.com, vpn.companyname.com  are getting redirected to https

Is this possible, if I run this code on Server after check-in it may work good..without any issue..
btanExec ConsultantCommented:
in fact the code is supposedly for the webserver per se.
The HSTS header and forceful redirection to the HTTPS scheme can both easily be implemented in the Application_BeginRequest event of the global.asax...
...Going back to the original example where packets sent over HTTP were sniffed, if the login had been over HTTPS and HSTS was used, it would have been impossible for the browser to issue requests over HTTP for the next 500 seconds even if explicitly asked to do so. Of course this structure then disallows any content to be served over HTTP but in many cases, this is precisely the scenario you’re looking to achieve.
You may want to sniff the http header and packet via fiddler tools or browser developer tool the flagged error for failure to redirect in your localhost testing. Best to test on staging prior to production on the redirect. As for the code specific to "Strict-Transport-Security", not all browser are supported though
Steve BinkCommented:
... or you could try using URL Rewrite.
Dinesh KumarAuthor Commented:
Its a known issue in IE9, it seems to be so we need to do attached settings so that site opens up.
IE9.PNG
btanExec ConsultantCommented:
thanks for sharing - this is in fact CORS as in the below (for various browser and IE10 above) can add in the CORS http hdr enable cross-origin requests. The IE9 config included as also captured (but in diff zone) ..http://www.webdavsystem.com/ajax/programming/cross_origin_requests

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Dinesh KumarAuthor Commented:
Thank you..
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SSL / HTTPS

From novice to tech pro — start learning today.