Problem Solved: Cloudfront is redirecting to the Origin
A guide to set up cloudfront properly
Problem Scenario:
Yesterday I tried to set up a Cloudfront CDN for my website. When I test it by browsing xxxxxxxx.cloudfront.net/image.jpg, it redirected me to the original image www.whitehorseforest.com/image.jpg instead of serving the cache copy of the image. (Hence the url in the browser is shown as www.whitehorseforest.com/image.jpg instead of xxxxxxxx.cloudfront.net/image.jpg)
I tried to do a Google Search on this problem but not able to get a clear answer so I believe it would be useful for any of you who faced the same issue.
Behind the Scene:
The reason for this to happen is because of the following fact:
1.) I set redirect rules on my server side to redirect non-www site to www
2.) The CDN will cache the redirect response, instead of following the redirect to cache the destination.
3.) My CDN origin is set to whitehorseforest.com
So when I enter. xxxxxxxx.cloudfront.net/image.jpg, it will look for the cache of. whitehorseforest.com/image.jpg
Since the response of whitehorseforest.com/image.jpg is a redirect to www.whitehorseforest.com/image.jpg
So the browser will be redirected to www.whitehorseforest.com/image.jpg instead of serving the cached image
Solution:
There are many way to solve the problem and the rule of thumb is never let the CDN to hit the redirect response.
In my case, I simply changed the CDN origin to be www.whitehorseforest.com. Then when we hit xxxxxxxx.cloudfront.net/image.jpg, the CDN will look for the cache of www.whitehorseforest.com/image.jpg, which is the actual image response instead of a redirect response.
Similarly, this could happen to a http -> https redirect set up in the server. My fix to this is in origin setting, change it to “Https only” to make sure CDN never hit the redirect. Also, you may want to change the Viewer Protocol Policy in Cloudfront behaviour setting to “Redirect http to https” to make sure you can always get a cache.


Hope this can solve your problem. Please let me know if there is any other possible fix to this problem!
