Non www to www with https and AWS load balancer

amazon-web-servicesdomain-name-system

my company bought a domain a while ago at company X (Gandi, to be specific).

Our goal today is to serve a website through a unique url: https://www.example.com.

So, we should make the following redirections:

http://example.com -> https://www.example.com
http://www.example.com -> https://www.example.com
https://example.com -> https://www.example.com

Here is a quick drawing I made to describe our architecture:

enter image description here

As you can see, we have a load balancer between our EC2 instance and our users in order to handle our SSL certificate.

Problem is: I think that the load balancer can only be accessed through a CNAME entry. And I can't configure a CNAME entry for the root domain.

The redirection from non www to www is made at the EC2 level. So everything works great for http://example.com and http://www.example.com:

enter image description here

I can't do the same with https://example.com because there is no cert on the EC2 instance and the user would face a security alert saying that the cert is invalid.

How can I get out of this madness?

Possible solutions I came with:

  • Transfer my domain from company X to Amazon. I don't like this solution because I like company X and I'm afraid of transfering the domain.
  • Generate a free certificate for my EC2 instance in order to make the redirection. I don't like this solution because it makes me maintain two certificates.

Thank you all for your tips!

Best Answer

Background - Route 53

You don't need to transfer your domain to AWS, but one thing that might help is to use the AWS Route53 DNS service. It has the concept of an "alias record". This record type acts like a CNAME and can work at the domain root. This is very useful when you're using AWS load balancers.

This won't solve your problem, exactly. You still need to have a valid certificate for the non-www domain, and you still need to issue a redirect. It might form part of a solution though.

R53 is pretty cheap - $0.50 per month, and $0.40 per million queries.

Solution - Certificate SAN

Another option is to have a certificate that includes both your www and non-www domain name. This is called an Subject Alternative Name (SAN) and is trivial to do. Let's Encrypt does these and they're free. This way you can have your EC2 server do the redirect https://example.com -> https://www.example.com

Putting it together

I suspect that using an alias record and changing your certificates you can have the load balancer or Cloudfront do your redirect for you. That saves the EC2 instance doing it, and is a bit faster.