I have a 301 set up which redirects http://domain.com to http://www.domain.com (http://www.domain.com$S$Q) but if I browse to https://domain.com I get an SSL error (as it expects www.domain.com).
Is there any way to make it redirect before the browser throws a cert error?
Yes, but not how you think.
If you can't do that, you're out of luck, unfortunately. You can't use HOST headers to differentiate between the two requests, because that's far too late (thus, separate IP addresses). And unless you have a valid certificate, the browser is going to choke, so you also need the 2nd cert.
There's no way around these requirements, I'm afraid.
I had exact same requirement like redirect all https://domain.com to https://www.domain.com and also redirect all http to https, here how I achieved and get it working IIS 8.5. I used following code in web.config file:
This worked like charm. Actually I generated above code in web.config by installing "URL Rewrite Module" using Web Platform Installer. After installation I found this module in IIS 8.5 then I added new rules. Hopefully, you can directly write this code in your web.config to get things done.
There is a way round it. You can get a single cert for both www.domain.com and domain.com. Then you can use a regular redirect. These multi-domain certificates are generally more expensive though.
I setup both domains each with their own conf files, (shared)cert, and separate home dirs then added an html meta refresh in the index.html at domain.com to redirect to www.domain.com. It works but perhaps theres a better way.
On the certificate for www.domain.com you will need to add a SAN entry for domain.com. Your issuer will reissue the certificate. The certificate will work for the name once it is added as a SAN to the certificate.
A SAN entry is a Subject Alternative Name. You can add several SANs to a certificate.
Here is more info: https://www.digicert.com/subject-alternative-name.htm