Host a static web application in AWS S3

We will host our static website in AWS S3.

Install the AWS SDK Node.js module

 npm install aws-sdk

Configure the AWS CLI with the access key and secret key in the ~/.aws/credentials file to access your AWS account.

Host the static website of the client in an S3 bucket

Create an S3 bucket using the AWS console

To be able to use Route 53 to route traffic to this S3 bucket, make sure you name the bucket to match the website address, like example.com, and it is created in the region of your choice.

Enable public access to the bucket

Click the bucket name, select the Properties tab and click Static website hosting

Select Use this bucket to host a website

Enter the name of the index and error pages, and copy the URL of the bucket

Add the S3 bucket policy

On the Permissions, Bucket Policy tab enter the bucket policy. Replace MY_BUCKET_NAME in the script with the bucket name.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::MY_BUCKET_NAME/*"
            ]
        }
    ]
}

Upload the client website to the S3 bucket

Copy the contents of the client/dist folder into the bucket. The webpack local test server deletes the contents of the dist folder, so you always have to copy the error.html file there before the upload to S3.

pushd client

# Copy the assets to the dist directory
cp error.html dist/
# Upload to S3
aws s3 cp dist s3://MY_BUCKET_NAME --recursive

popd

Test the static website

Navigate to the address you have copied from the Static website hosting page

Create an SSL certificate

Modern browsers display the “Not secure” message in the address line if the site is not accessed through HTTPS. To use HTTPS we need an SSL certificate.

  • Open the Certificate Manager and click the Request a certificate button
  • Select Request a public certificate

To use the certificate for www.mysite.com or api.mysite.com create the *.mysite.com wildcard certificate. The wildcard certificate does not work without the subdomain, to attach the certificate to mysite.com create a separate certificate for mysite.com.

Create a CloudFront Distribution

To be able to attach an SSL certificate to the URL we need a CloudFront Distribution in front of the S3 bucket.

  • Open the CloudFront console and click the Create Distribution button
  • Select the Web delivery method
  • Select the S3 bucket which contains the files of the static site
  • Enter the URL of your website into the Alternate Domain Names (CNAMES) field
  • Select the SSL certificate you have created above. Make sure you specify the entry point of the site (index.html) as the Default Root Object

Leave a comment

Your email address will not be published. Required fields are marked *