DEV Community

Cover image for Hosting a Hugo site on AWS S3 and CloudFront
Karl Eriksson
Karl Eriksson

Posted on • Originally published at mocki.io

Hosting a Hugo site on AWS S3 and CloudFront

In the early days we used Wordpress as our go-to-CMS. Over the years however we have seen examples of these blazing fast lightweight sites built on top of static site frameworks such as Hugo. These sites had the following advantages over Wordpress:

  • Super fast (no server side logic at all)
  • Secure (there is no login system to brute force - it's just static files)
  • Easy to version control
  • Easy and cheap to host (no need for a database or backend hosting)

So for the site you are looking at right now (Mocki.io) we chose to go with Hugo. We picked it up quickly and started building out the site still amazed at the speed it serves content. There were however some challenges. Our tech stack is hosted 100% on AWS and we quite like it. Naturally, we chose to deploy this site to AWS as well and the clear choice was S3 which is a static file hosting service. For CDN we chose AWS CloudFront which is super powerful. Deploying the site was quick and S3 + CloudFront served the content at blazing speed.

Of course there were challenges... our previous site did not have trailing slashes in the URL (example.com/page) while Hugo forced us to have trailing slashes (example.com/page/). For SEO reasons we wanted the exact same URL structure as the previous site. When looking in the Hugo documentation it did not have support for that. We also wanted to redirect www.example.com to example.com to make sure there was only one domain you could reach our site on.

To solve this we used Lambda@Edge. An AWS Lambda function is a piece of code that is deployed and run in the cloud. Lambda@Edge is a Lambda function that you can trigger when someone accesses your site through CloudFront. So we wrote a Lambda that removes the trailing slash and redirects the www domain to the non www domain. It also routes the requests from CloudFront to S3 so that the correct HTML-file is fetched from S3.

We put the entire setup in a CloudFormation template that you can deploy in one single command. You can access the code to deploy your own Hugo site on AWS here: https://github.com/keaeriksson/hugo-s3-cloudfront.

The result solved most of our SEO challenges that we had while still keeping the advantages of building the site with Hugo.

Feel free to reach out if you need more advice on hosting static sites on AWS using the chat in the bottom right.

Cheers!

Top comments (1)

Collapse
 
omar16100 profile image
omar shabab

Thanks for sharing Karl!
I was looking for something similar