DEV Community

Cover image for Use CloudFront to serve a static website hosted on Amazon S3
Cindy Le
Cindy Le

Posted on • Updated on

Use CloudFront to serve a static website hosted on Amazon S3

Part 2/n of the Cloud Resume Challenge

Chunk 1: Building the frontend

After configuring the Next.js website on S3, you'll notice that the website endpoint http://cindy-crc.s3-website-us-east-1.amazonaws.com/ is HTTP. This is because the website URL should use HTTPS for security, and this is where we'll need to use CloudFront.

Stack:

  • Next.js
  • Amazon S3
  • Amazon CloudFront

As you'll remember from the previous blog, you'll need to remove any Bucket policy attached to the S3 bucket and Block all public access to continue with this.

We will be using a REST API endpoint as the origin, with access restricted by an Origin Access Identity (OAI).

Create the CloudFront Distribution

I mostly followed Use CloudFront to serve a static website hosted on Amazon S3

  1. In the Amazon CloudFront console, choose Create distribution
    • Origin domain: cindy-crc.s3.us-east-1.amazonaws.com (from the dropdown menu)
    • Name: cindy-crc.s3.us-east-1.amazonaws.com (should be autofilled)
    • S3 bucket access: Yes use OAI (bucket can restrict access to only CloudFront)
    • For Origin access identity, select Create new OAI and choose the newly created OAI
    • Bucket policy: Yes, update the bucket policy
    • Default root object - optional: index.html
  2. Click Create distribution and wait for the Last modified status to go from Deploying to Date. This may take ~5 minutes
  3. You should be able to visit the Distribution domain name link https://d1ij0wngzhbeyc.cloudfront.net and see the resume website

Troubleshooting

If you're getting an Access Denied error, it's probably due to Bucket policy. You should be blocking all public access and only allowing your CloudFront Distribution to access your S3. The S3 bucket policy should look like

{
    "Version": "2008-10-17",
    "Id": "PolicyForCloudFrontPrivateContent",
    "Statement": [
        {
            "Sid": "1",
            "Effect": "Allow",
            "Principal": {
-                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity Distribution-ID"
+                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E392Q20ZNZ7N4X"
            },
            "Action": "s3:GetObject",
-            "Resource": "arn:aws:s3:::Bucket-Name/*"
+            "Resource": "arn:aws:s3:::cindy-crc/*"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)