You cannot do this with a single certificate. The reason is because the web server needs to do an ssl handshake before redirecting it, so you will always have a problem with an invalid certificate.
You really have only one option - circle both www and no www with the certificate and redirect. You can do this in several ways: get a certificate with several domain names called a SAN certificate, or get two certificates: one for www and one without. However, in the second case, you will need two web servers with different IP addresses to complete your task.
An alternative approach that uses me myself is to not worry about it. Ask users to go to the regular http website and redirect themselves when an SSL connection is required. This is what amazon.com does. They want you to browse http, and they only redirect you to SSL when you buy something. Their certificate is also valid only for www, just go to https://amazon.com and you will see that their certificate is not valid without www
source share