Static Hosting on S3 w/ Cloudfront Distribution.
Nikolai Main
Posted on October 24, 2024
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
Data flow
- User makes a request to yourdomainname.com
- Route53 resolves the request and passes it to CloudFront.
- CloudFront reroutes any HTTP traffic to HTTPS and returns tls certificate to validate.
- If nothing is cached in CloudFront - Or your caching settings require it - The S3 bucket is queried and retrieves the website.
- Content is sent to user.
Creation Process
S3
- Create new S3 bucket.
- Turn 'block public access' off.
- Under object ownership enable ACLs.
- 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.
- When uploading your website, make sure to enable public access for all necessary files.
Route 53
- Register a new domain with Route53
- Create hosted zone
- Name the hosted zone with your domain name.
- Ensure the allocated ns (name server) records match the registrars.
ACM
- 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.
- Validate your certificate by creating records in your Route 53 hosted zone.
Cloudfront
- Create CloudFront distribution
- Link S3 bucket - Use as website endpoint
- Redirect HTTP to HTTPS.
- Link the certificate you created in ACM.
- Once created go into settings and add alternate name yourdomainname.com
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.
- Create lambda function with your your S3 bucket as the trigger. More specifically ‘all object create events’ and ‘all object delete events’
- 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
}),
};
}
};
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.
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
November 18, 2024