Automatic redirect from HTTP to HTTPS

IIS (Internet Information Server) doesn’t have a way to automatically redirect HTTP traffic to HTTPS if SSL encryption is enabled for a site. So if you’ve got a site that users are supposed to access by typing in, but they type in or or just, they’re going to get a pretty ugly error message that looks like this:

What can you do? Well, there are two ways of going about it, and both of them are hacks, but they do the job just fine. I prefer method 2 myself.

Method 1:

Make sure the original site (the one with SSL encryption) is listening only on port 443 for the IP address you’ve assigned to it. Now create a separate site using that same IP address, and make sure it only listens on port 80. Create a single file at the root level and call it default.htm or default.asp. If you want to use HTML, then use a meta refresh tag. If you want to use ASP, use a redirect. I’ll give you examples for both below.

<meta http-equiv="Refresh" content="0;URL=" /> 


<% Response.Redirect("") %>

Don’t forget to enclose each line in its proper brackets. This method works great, but it has one shortcoming. If the site visitor chooses to go to, they’re going to get forwarded to the root-level of the HTTPS site, because that’s the nature of the script. It doesn’t differentiate between the page addresses. So you may ask yourself, isn’t there some other way of doing this? Yes, there is.

Method 2:

This method doesn’t require the creation of an additional site. All that you need to do for this is to create an HTML file — I call mine SSLredirect.htm — then point IIS to it using a custom error capture. First, here’s the code that you need to paste in that HTML file:

<script language="JavaScript">
<!-- begin hide

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

// end hide -->

Once you’re done editing the file, save it to the root level of your site, or to the root level of IIS (c:\inetpub\wwwroot\). Saving it to that general location lets you use that same file to fix the HTTPS redirection problem for all of the sites you host on a single server.

Now, in IIS 6, right-click on the site in question, go to Properties >> Custom Errors, and double-click on 403;4. Select File for Message Type, then browse for the file you’ve just created and click on OK. In IIS 7, click on your site, then double-click on Custom Errors, locate the Add link in the top right-corner, and add an error for 403;4, as shown in the image below.

IIS 7 Error Configuration

Once you’ve done this, your sites should automatically transfer HTTP traffic to HTTPS when it’s required, and the visitors won’t be forwarded to the root-level of the site. Instead, the URL will be remembered, and the page will simply be re-loaded using the HTTPS protocol. Come to think of it, you could write this in ASP as well, and avoid potential problems caused by browsers that have JavaScript turned off, but this code should work just fine for a lot of people.

70 thoughts on “Automatic redirect from HTTP to HTTPS

  1. Ryan Wyler says:

    I appreciate your article that got my brain cooking. I did a variation on this. I have some CGI that works on both the non-https site and https site. But I created this piece of code that goes in the section for pages I want to be in only HTTPS.

    function check_secure() {
    var httpsRE = /^https/i;
    if (!window.location.origin.match(httpsRE)) {
    window.location = "https://" + window.location.hostname + window.location.pathname +;

  2. Amit says:

    Thanks Raoul and Troy Hinkle for the solution of redirection and IE 7 issue.
    This was a really useful thread

  3. Troy Hinkle says:

    Thanks to Raoul for the post. This was the most clear approach of the many articles I’ve read on this subject.

    Method 2 worked for me when browsing an IIS6 site with Firefox, Chrome, and Safari, but didn’t work with Internet Explorer 8 running on XP (got a different 403 access error).

    This adjustment sorted the issue for me:
    Place the SSLredirect.htm in the wwwroot dir

    Use “URL” rather than “FILE” when choosing the new custom error page, and designate the URL as “/SSLredirect.htm”

    Go to the properties of the SSLredirect.htm file within IIS and turn-off the require secure channel checkbox just for this single file

  4. VinodK says:

    Hi Raoul
    I am using IIS7 and I have both http and https sites created. I have not assigned any IP addresses to them and configured as “all unassigned” but the host name provided as

    I could do a https redirection to my site Please replace with my website name in the below code that you provided so that I can easily follow that. I have created sslredirect.html at the root of wwwroot folder.

    • VinodK says:

      Sorry .. I just missed NOT in my last post.

      In the beginning of second paragraph, I mean to say “I could NOT do A https redirection”

      sorry for the confusion.

  5. on an apache server one would use mod_rewrite to do this redirect at a server level. it’s a better approach than using javascript because:

    - the redirect happens before page load
    - you can return a 301 header for Google friendliness
    - it’s easier to manage conditional logic (eg: if the redirect is only required for certain pages)

    there are a couple of commercially available extensions for IIS which provide mod_rewrite functionality:

    i haven’t specifically tried them for https redirection but i would expect it to work.

  6. I use this code to redirect to the same page and turn the encryption on (classic asp):

    0 Then sRedirect = sRedirect & "?" & sQString
            if method = "POST" then
                Response.Write ""
                for x = 1 to Request.Form.Count()
                    tname = Request.Form.Key(x)
                    tvalue = Server.HTMLEncode(Request.Form.Item(x))
                    Response.Write "" & vbCrLf
                Response.Write ""
                Response.Write "" & vbCrLf
                Response.Write "document.f.submit();" & vbCrLf
                Response.Write ""
                Response.Redirect sRedirect
            end if
        end if
  7. Pingback: exchange server
  8. karuna says:

    I need to complete the job of aoto switching from http to https by Wednesday 11/03/2010. Any help please?

  9. karuna says:

    In IIS under DefaultWebSite created a virtual directory for my project and set it’s custom errors 403;4 to the html that I wrote (with your script in it. nothing else). It still shows http:// not https://. Am I doing anything wrong? Please help me.

  10. karuna says:

    I did exactly what you have asked to do for a web project not site. It didn’t work. I am getting at the execution time onlt http://… not https://…. Is there a difference between project and site. Please let me know ASAP.

    Thanks in advance.


    • Every time someone says this doesn’t work, they haven’t implemented it properly. It works. It’s worked for hundreds of people. If it doesn’t work for you, there’s something else going on somewhere on your web server.

  11. Amit T says:


    If I type then I am getting redirected to proper page. How this is possible? I am using IE8.


  12. Hogan says:

    @Amit T:

    This is not your code, you can check your server logs.

    IE6 requires a www OR the http:// prefix for urls.

    Thus or just won’t work in IE6 no matter what code you put server side.

  13. Amit T says:


    I am having same HTTPS redirection problem. If I type or then I am getting an error page, I need to type complete URL as I tried the above code snippet but it didnt work out for me. I am using IIS 6.0. The IE error which I am getting is given below. Please send me some solution on this.

    HTML file content which I am using are:

    function goElseWhere()
    var oldURL = window.location.hostname + window.location.pathname;
    var newURL = “https://” + oldURL;
    window.location = newURL;


    Browser error when I type or are:

    Internet Explorer cannot display the webpage

    What you can try:
    Diagnose Connection Problems

    More information

    This problem can be caused by a variety of issues, including:

    •Internet connectivity has been lost.
    •The website is temporarily unavailable.
    •The Domain Name Server (DNS) is not reachable.
    •The Domain Name Server (DNS) does not have a listing for the website’s domain.
    •There might be a typing error in the address.
    •If this is an HTTPS (secure) address, click Tools, click Internet Options, click Advanced, and check to be sure the SSL and TLS protocols are enabled under the security section.

    For offline users

    You can still view subscribed feeds and some recently viewed webpages.
    To view subscribed feeds

    1.Click the Favorites Center button , click Feeds, and then click the feed you want to view.

    To view recently visited webpages (might not work on all pages)

    1.Click Tools , and then click Work Offline.
    2.Click the Favorites Center button , click History, and then click the page you want to view.

  14. Oyadiran Onaopemipo says:

    Thanks a bunch………Combining the above code and replacing var oldURL = window.location.hostname + window.location.pathname; with var oldURL = window.location.hostname + window.location.pathname + it works fine on all the browsers without Issues.

    Use the code below it works perfectly without any hitch

  15. Hogan says:

    I have a typo above, here is working production code:
    (if pre does not work then you will have to use view source or something…)

    The page must be viewed over a secure channel
      document.location = document.location.href.replace(/^http:\/\//i, "https://");
  16. Hogan says:

    2 Things:

    1) @Raoul: Why wrap the functionality in a function? What good does this provide? Wouldn’t a comment serve the same purpose?

    2) @Amol: I think the following javascript is better for your approch, using regEx it says “Case insensitive replace of any string that starts with http not followed by s”:

    // Javascript redirect to https using regEx for use in a 403-2 error file.
    window.location = window.location.href.replace(/^http[^s]/i,’https’);

  17. David says:

    Thank you for sharing this solution Raoul. I used method 2 and worked for me (including IE8, and Google Chrome).
    Updated your code to XHTML 1.1:

    • Sorry David but WordPress won’t let you post code in the comment box. Perhaps you can upload your code as a text file to your website, and post the link to it?

  18. JN_Dev says:

    Hello Raoul,

    Your second Option is not working dear. I am getting Error like this on IE 8:

    Secure Channel Required
    This Virtual Directory requires a browser that supports the configured encryption options.

    What i have done is:
    [1] I have two websites/virtual-directories in wwwroot folder (Live), (Test).
    [2] In IIS manager, right click on the TEST site -> Properties -> Directory Security -> Secure Communications (Edit & Check the ‘Require SSL channel’) -> OK.
    [3] Created a file ‘SSLRedirect.html’ in TEST sites root folder (Used same code as shown by you)
    » In IIS Manager, RightClick on Test Site -> Properties -> Custom Erros [Set URL to '/TEST/SSLRedirect.html' for Error Code 403;4].

    Now when i run the site on HTTPS it works fine, while on HTTP, it shows me above message. I am using IE 8.

    Please reply ASAP. Its urgent for me.

  19. Amol says:

    More compact code:

    function redirectToHttps()


    var httpsURL = window.location.href.replace(‘http://’,’https://’);

    window.location = httpsURL ;



  20. Amol says:

    If you like to maintain the Query String values also then create the File with following code:

    function redirectToHttps()


    var httpURL = window.location.href.replace(‘http://’,”);

    var httpsURL = “https://” + httpURL ;

    window.location = httpsURL ;



  21. Kevin says:

    Mmzz, the forum removes tags, this was missing in the top of the file:

    <%@ language=”VBScript” % &rt;
    Option Explicit

    If Response.Buffer Then
    Response.Status = “200 Ok”
    Response.ContentType = “text/html”
    Response.Expires = 0
    End If

    <script type=”text/javascript”&rt;

  22. Kevin says:

    For anyone who did the custom error redirect thing, and got the Forbidden 403 error, use a .asp file instead (e.g. httpredirect.asp), enable ASP and redirect 403.4 error to this ASP file.

    File this file with the following code:

    function redirectToHttps()


    var httpURL = window.location.hostname+window.location.pathname;

    var httpsURL = “https://” + httpURL ;

    window.location = httpsURL ;



    And you’re done!
    Even IE works, because the 403 headers are emptied before sending.

  23. Michael -

    The issue with the method you describe is that our website handles both regular and secure ports. So I can’t just automatically redirect HTTP traffic to HTTPS.

  24. Joe D'Souza says:

    I had to choose Method 2 because my URL’s are dynamically generated for the most part with only the server name remaining constant.. so replacing http:// with https:// from the rest of the URL seemed to be a better idea.

    So I used the script you suggested to create the SSLredirect.htm file:

    However a small part of your instruction after that, is not correct and didn’t work at least in IIS 6. I’m not sure if you got it working in IIS 7 and hence your instructions may be based on IIS 7???

    According to your instructions:
    “Now, in IIS 6, right-click on the site in question, go to Properties >> Custom Errors, and double-click on 403;4. Select File for Message Type, then browse for the file you’ve just created and click on OK.”

    If I do this in IIS 6 it does not work and I get a 403 Forbidden error. However instead of selecting File for Message Type, if I select URL and then enter /SSLredirect.htm as the URL, it works..

    Just thought I may share my experience, just in case you want to test it and re-edit your article..



  25. michael says:

    ISA Server will do the redirects automatically. On the Listener properties, choose the Connections tab. Check Enable HTTP connections on port: 80 and Enable SSL(HTTPS) connections on port: 443. Then under HTTP to HTTPS Redirection choose Redirect all traffic from HTTP to HTTPS.

  26. Glad it worked out for you, Ron. I haven’t worked with ISA yet, usually our network guys handled it in the past, so I wasn’t sure what to say when you asked your question.

  27. Actually, I figured it out. Apparently the ISA will cause an endless loop if you do a redirect in this fashion. But it can be easily remedied by instructing it to do a “do-nothing” redirect. The following article explains it well:

    I did this and the javascript worked like a charm.

  28. Here’s a fun zinger. We’ve set up our site to operate through our ISA firewall. But apparently, the ISA not only thwarts all redirects, it won’t even display an HTTPS link for you – it’ll truncate the ‘s’. Meaning, if your webpage displays “” a viewer will only see “”.

    Anybody else have this issue or know how to get around it?

  29. That’s great, I didn’t know about those wildcard and suffix parameters. That means the redirection method should work just fine on a URL-by-URL basis.

    My redirection method won’t help your crawler, but what you can do, as I suggested in my previous comment, is to set up an alias for the server name inside SharePoint admin, where it’s mapped to port 80, not 443. I did it before, so I know it works. I can’t recall the details though, since it’s been a while. If you can, give Microsoft a call and ask them to help you set it up. What you want is to have a regular way for the site users to access the web app, where you’re enforcing HTTPS, and another way for the crawler to access the server, where you’re not enforcing HTTPS.

  30. San says:

    Not sure if its the same thing or not…but this is what I tried..I extended y sharepoint web application that was running in port 443 to port 80, so now I got two web applications, port-443 and port-80. Now I used IIS manager window to open the web application that is running at port 80, Properties ->Home Directory -> select radio button “A redirection to a URL”. Then entered the https://server_name in the “Redirect to” text box. And then select “permanent redirection for this resource”.

    Now when user browse the site, http://server_name, it redirects the user to https://server_name. But my sharepoint search stop working after these changes ..not sure why.

    But I wanted to know how this is different what you have described above?


    • It’s not quite the same thing. I don’t think your redirection is a URL-by-URL redirection. In other words, if you go to, where is your server, then you won’t be redirected to You’ll be redirected to

      SharePoint search stopped working because the site crawler can’t function on port 443. It needs to have port 80 open. It’s been a while since I tinkered with the SharePoint admin, so I can’t help you there, but I suggest you open a case with Microsoft and ask them to show you how to set up an alias web app only for search, so you can enforce HTTPS for the regular site users.

  31. San, by all means, if you’ve found another, easier way to do the exact same thing, then please explain it to me.

  32. San says:

    IIS doesn’t have a way to automatically redirect HTTP to HTTPS??

    But I can do this without writing any of these script by using IIS settings Home Directory ->Redirect To

    How this is different from what u have suggested here?

  33. Paola DePaso says:

    oops, code didn’t display.
    var oldURL = window.location.hostname + window.location.pathname +;

  34. Paola DePaso says:

    I figured out my issue with the proposed code and for the redirect to pass on a string beginning with a question mark that specifies any query information in an HTTP URL.

    Here is my version of the above code:

  35. Jonathan Rosario says:

    Wow… after trying TONS of other ways (google IIS7 redirects), yours actually worked flawlessly.
    Thank you!

  36. Ambar says:

    This does not work in IE 7
    Though the response says redirect to HTTPS site the header still contains 403 – Forbidden.
    Firefox and Safari ignores the header for some reason whereas IE 7 chooses to give more importance to the header.

  37. Delroger, thanks for pointing that out! I finally figured out what’s happening and corrected the post. You’re on the right track. You see, WordPress, my site’s platform, will turn two sequential hyphens (–) into a single hyphen (-). When the WP engine parsed the content of the page, it did just that, and the code, when copied and pasted, will naturally cause errors. I’m sorry I couldn’t spot the problem until now.

  38. Nice bit of code – good way to handle that. Like Lee Robinson said, I also found the script causes errors as it stands though. I found that the line with the ‘begin hide’ comment needs to be removed or commented out with //.

    Thanks for a good, easy solution though!

  39. Lee, this method has been working great for me and for others, without fail, for some time. The only thing I can think of in your situation is that you didn’t really create a full-fledged HTML file where you pasted the code. Remember, it needs to be an HTML page, with beginning and ending html, head and body tags. You’d then paste the Javascript code inside the head tags and go from there. If you’re not sure how to write HTML or where to put the Javascript code, this is a good place to start.

  40. I have tried this with our SharePoint site. When I type in the site:, the little yellow triangle comes up and says there is an error in the script. I copied and pasted the script and visually verified it is the same. Any idea why this is not working? Can you show us the ASP version of it?



  41. Ed, I’m not sure about that. I’m not an SEO guru. I know the basics, but I don’t claim expertise in that area. I just wanted to help others by showing them how to do this once I figured it out. I searched around for a long time for a solution akin to mine, and couldn’t find anything.

    I believe an ASP redirect wouldn’t hurt SE rankings, since it happens on the server side, but I’m not sure about the others. Perhaps you can ask around in the Google newsgroups?

  42. I sell Domains and hosting on my site and I need to know if either of these two ways hurt page rank with Google? I’m looking for the correct way to redirect all traffic to SSL but I don’t want to do it with an error page. This way, my customers can have the comfort that their traffic will always be secure.


    Ed Rockwell – Owner
    CyberSpot, Inc.
    Domain Names, Domain Transfers
    Web Hosting, Email and more…

Comments are closed.