Hi guys, I haven’t written anything for quite some time due to lack of time (and laziness). In this article I’m going to share my experience on how to put a whole website, hosted on a EC2 instance, behind CloudFront.
If you want your website to have a global presence and to be accessed quickly anywhere around the world, even in China probably, AWS CloudFront is a great tool to do just that. CloudFront supports the distribution of both static and dynamic content, so you can pretty much set it up with any type of website.
Assume the website’s url is https://www.example.com. If you’re not using https, I suggest you do because it makes websites secure and it’s favored by search engines. You can do it for free by using services provided by Let’s Encrypt.
- Now, time to create a Distribution from your AWS Console.
- For delivery method, choose “Web”.
- In Origin Domain Name, enter the public DNS name of your EC2 instance. If the website uses https, select “HTTPS Only” for Origin Protocol Policy
- If your website uses https, select “Redirect HTTP to HTTPS” for Viewer Protocol Policy, otherwise select “HTTP and HTTPS”.
For Allowed HTTP Methods, select “GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE” if the website contains any dynamic content, such as forms or eCommerce elements.
For Cache Based on Selected Request Headers, select “Whitelist” and add “Host” to the whitelisted headers list. This is especially important if your webiste uses https.
- For dynamic site to work properly, all cookies and query strings will need to be forwarded.
- In Alternate Domain Names(CNAMEs), enter your domain name, in this case ‘www.example.com’. For SSL Certificate, select “Custom SSL Certificate”. Click the “Request or Import a Certificate with ACM” button to get a free certificate from AWS.
- Click the “Create Distribution” button to start the creation process. After about 10-15 minutes your distribution should be ready to use.
- Last but not least, modify your DNS record so that domain “www.example.com” points to the newly created CloudFront URL. In Route 53, it looks like this
Finally, to verify if everything has been setup correctly, open your website in a browser and have a look the Response Headers in the browser console, you should be able to see entries like x-amz-cf-id and x-cache.