Search code examples
amazon-web-servicescachingproxyamazon-cloudfrontbare-domain

Root domain behind AWS CloudFront


As per this Amazon's article I was trying to make the whole WordPress website work behind AWS CloudFront. Not just the static files but the whole website (it can be done with setting up proper cache behaviors). However if you use the bare domain (example.com, without www) it seems that's impossible.

Namely, if the origin of a CloudFront distribution is example.com, and if you put a CNAME for example.com in that same distribution CloudFront will sporadically produce 403 Error. After some digging I found out that this is expected behavior since with this setup, where origin and the CNAME values are the same, CloudFront will look for the origin onto itself and produce error.

So how can one use naked domain and use CloudFront as a proxy at the same time?


Update:

I've implemented the origin.example.com solution suggested in the comments. I was getting an error but now it works.

  1. The origin in the CF distribution is origin.example.com.
  2. CNAME in the CF distribution is example.com.
  3. In the Cache Behavior settings in the CF distribution the Host header is whitelisted.
  4. In DNS origin.example.com points to the server's IP with an A record.
  5. In DNS example.com points to the CF distribution with an ALIAS-A record.

The only beef I have with this workaround is that this way the origin server's IP address is discoverable on the net. A script kiddie can accidentally access origin.example.com and the server's true IP address is in the open, thus you're prone to DDoS. One of the many benefits of a proxy is that with it you're hiding the true server's IP address.

I'm currently using Cloudflare as a proxy mainly because of that reason. In the past I was hit with massive DDoS attack and my server's IP address was null-routed by the host, so I had to quickly hide behind Cloudflare and change the server's static IP. No headaches since then. I wanted to switch to CloduFront but using the bare domain seems not viable.


Solution

  • You have to create another hostname in DNS, pointed to the instance, such as origin.example.com. But the instance does not need to know about this name.

    Create a CloudFront origin using this new hostname as the origin domain name, and then in the Cache Behavior, whitelist the Host header for forwarding to the origin.

    In DNS, point example.com only to CloudFront.

    CloudFront will then use the alternate name to find the instance's actual IP address, but will preserve the original hostname (example.com) in the request that is sent to the origin.