Static Hosting on S3 w/ Cloudfront Distribution.

neakoh

Nikolai Main

Posted on October 24, 2024

Static Hosting on S3 w/ Cloudfront Distribution.

AWS offers a free and easy solution for hosting static sites. Possible uses for a static site include personal blogs, portfolio sites, or even as a disaster recovery option - If your main service goes down, you can automatically route users to a static site that explains the situation.

The process of creating a static site is straightforward and can be integrated with CloudFront, a caching service that speeds up retrieval by storing website data at edge locations closer to your users. Additionally, Amazon's free TLS certificate service, ACM, can be implemented to provide HTTPS validation for the site.

Components Used

  • Route 53 - DNS service
  • Cloudfront - Caching service
  • Certificate manager - Provides HTTPS certificates
  • S3 - Bucket storage.
  • Lambda (Optional) - Create a Lambda function to invalidate the cloudfront cache each time you make changes to your S3 bucket

Blank diagram.jpeg

Data flow

  1. User makes a request to yourdomainname.com
  2. Route53 resolves the request and passes it to CloudFront.
  3. CloudFront reroutes any HTTP traffic to HTTPS and returns tls certificate to validate.
  4. If nothing is cached in CloudFront - Or your caching settings require it -  The S3 bucket is queried and retrieves the website.
  5. Content is sent to user.

Creation Process

S3

  1. Create new S3 bucket.
  2. Turn 'block public access' off.
  3. Under object ownership enable ACLs.
  4. Go to your bucket’s properties and scroll all the way to the bottom > Enable static hosting.
    • Make sure you set your index document properly, ensuring it’s named correctly and isn't nested in any folders.
  5. When uploading your website, make sure to enable public access for all necessary files.

Route 53

  1. Register a new domain with Route53
  2. Create hosted zone
    • Name the hosted zone with your domain name.
    • Ensure the allocated ns (name server) records match the registrars.

image.pngDomain Registrar

image.pngHosted Zone

ACM

  1. Request certificate from ACM - When requesting a certificate from ACM, make sure your region is set to N. Virginia (us-east-1). This is important because Amazon's administrative infrastructure is primarily located in this region, and certain services, like CloudFront, require certificates to be issued from us-east-1.
  2. Validate your certificate by creating records in your Route 53 hosted zone.

image.png

Cloudfront

  1. Create CloudFront distribution
  2. Link S3 bucket - Use as website endpoint
  3. Redirect HTTP to HTTPS.
  4. Link the certificate you created in ACM.
  5. Once created go into settings and add alternate name yourdomainname.com

image.png

Finally go back to Route53 and create an A record aliased to your cloudfront distribution.


Lambda (Optional)

Create a lambda function to automatically invalidate (Refresh) your cloudfront cache whenever there is a change in your S3 bucket. This is useful regardless of what you use the static site for but particularly so if youre hosting a blog where you’re regularly changing the site.

  1. Create lambda function with your your S3 bucket as the trigger. More specifically ‘all object create events’ and ‘all object delete events’
  2. Go to IAM and find the role created and provide it access to S3 and Cloudfront.
const AWS = require('aws-sdk');
const cloudfront = new AWS.CloudFront();
const DISTRIBUTION\_ID = '<yourcloudfrontdistributionid';
exports.handler = async (event) => {
    console.log('Event:', JSON.stringify(event, null, 2));
    const params = {
        DistributionId: DISTRIBUTION\_ID,
        InvalidationBatch: {
            Paths: {
                Quantity: 1,
                Items: \['/\*'\], // Invalidates all object in CloudFront
            },
            CallerReference: \`${Date.now()}\`,
        },
    };
    try {
        const data = await cloudfront.createInvalidation(params).promise();
        console.log('Invalidation request sent:', data);
        return {
            statusCode: 200,
            body: JSON.stringify({
                message: 'Invalidation request submitted successfully.',
                invalidationId: data.Invalidation.Id
            }),
        };
    } catch (err) {
        console.error('Error invalidating cache:', err);
        return {
            statusCode: 500,
            body: JSON.stringify({
                message: 'Error invalidating cache.',
                error: err.message
            }),
        };
    }
};
Enter fullscreen mode Exit fullscreen mode

Final Notes

Overall, Setting up a static site on AWS using S3 provides a simple, robust and efficient hosting solution. This configuration ensures high availability and fast content delivery through CloudFront's global network, while ACM secures your site with HTTPS. Automating cache invalidation with a Lambda function keeps your content up-to-date without manual intervention, making it ideal for frequently updated sites. This may not be the most complex of set-ups in AWS, but a useful one nonetheless.

💖 💪 🙅 🚩
neakoh
Nikolai Main

Posted on October 24, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related