AWS

Hosting A Static Website On AWS using S3

37
0

In this post, I’ll walk you through the process of hosting a static website on AWS using Amazon S3. I’ll also cover what a static website is and then delve into the steps required to set up your site.

What is a Static Website?

A static website is a collection of web pages with fixed content, presenting the same information to every visitor. Unlike dynamic websites, static sites do not engage in server-side processing or database connectivity. They consist of HTML, CSS, and sometimes JavaScript, rendering pre-built pages directly to users. This simplicity offers advantages in specific scenarios, emphasizing efficiency and rapid page loading.

Example of a Static Website

Imagine a small, local restaurant that wants to establish an online presence. They decide to create a static website to showcase their menu, opening hours, and contact information. In this scenario, the content on each page is fixed and doesn’t change frequently. Users can navigate through the site to view the menu, learn about the restaurant, and find contact information. The simplicity and stability of a static website make it an excellent choice for businesses with relatively unchanging information.

Key Components and Steps to Host a Static Website on AWS

Amazon S3 for Storage

Amazon S3 (Simple Storage Service) is a highly scalable object storage service ideal for hosting static websites.

  1. Create an S3 Bucket:

Navigate to the S3 service in the AWS Management Console.

Create a new bucket with a unique name. Ensure the bucket name adheres to DNS naming conventions.

Enable static website hosting in the bucket properties.

Specify the index document (e.g., index.html) and error document (e.g., error.html).

  1. Upload Static Files:
  • Upload your static files (HTML, CSS, JavaScript, images) to the S3 bucket. You can do this through the AWS Management Console or using AWS CLI for automation.
  1. Set Permissions:

Update the bucket policy to make the contents publicly accessible. A sample bucket policy to allow public read access:

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

CloudFront for Content Delivery

Amazon CloudFront is a content delivery network (CDN) that accelerates the distribution of your static content.

  1. Create a CloudFront Distribution:
  • In the AWS Management Console, navigate to CloudFront and create a new distribution.
  • Set the origin domain to your S3 bucket’s website endpoint.
  1. Configure Origin Settings:
  • Set the Origin Protocol Policy to HTTP.
  • Configure caching behavior and specify the default root object (e.g., index.html).
  1. Set Up SSL/TLS:
  • Use AWS Certificate Manager (ACM) to create or import an SSL/TLS certificate.
  • Associate the certificate with your CloudFront distribution for secure HTTPS communication.

Route 53 for Domain Management

Amazon Route 53 is a scalable DNS web service.

  1. Register or Transfer a Domain:
  • In Route 53, register a new domain or transfer an existing one to Route 53.
  1. Create a Hosted Zone:
  • Create a hosted zone for your domain.
  • Add DNS records to point your domain to the CloudFront distribution. Typically, you would add an A record with an alias to the CloudFront distribution.

AWS Certificate Manager for SSL/TLS Certificates

AWS Certificate Manager (ACM) simplifies the management of SSL/TLS certificates.

  1. Request a Certificate:
  • In ACM, request a new certificate for your domain.
  • Choose DNS validation for ease of use.
  1. Validate the Certificate:
  • Add the provided CNAME records to Route 53 to validate ownership of the domain.
  1. Associate the Certificate:
  • In CloudFront, associate the validated certificate with your distribution.

Infrastructure as Code (IaC) with AWS CDK

AWS Cloud Development Kit (CDK) allows you to define cloud infrastructure using familiar programming languages.

  1. Install and Configure AWS CDK:

Install the CDK toolkit using npm:

npm install -g aws-cdk
  1. Write a CDK Application:

Define your S3 bucket, CloudFront distribution, Route 53 configuration, and ACM certificate in a CDK stack. Here’s an example in TypeScript:

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';
import * as route53 from 'aws-cdk-lib/aws-route53';
import * as certificatemanager from 'aws-cdk-lib/aws-certificatemanager';

export class StaticSiteStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const siteBucket = new s3.Bucket(this, 'SiteBucket', {
      websiteIndexDocument: 'index.html',
      websiteErrorDocument: 'error.html',
      publicReadAccess: true,
      removalPolicy: cdk.RemovalPolicy.DESTROY,
    });

    const certificate = new certificatemanager.Certificate(this, 'SiteCertificate', {
      domainName: 'example.com',
      validation: certificatemanager.CertificateValidation.fromDns(),
    });

    const distribution = new cloudfront.CloudFrontWebDistribution(this, 'SiteDistribution', {
      originConfigs: [{
        s3OriginSource: {
          s3BucketSource: siteBucket,
        },
        behaviors: [{ isDefaultBehavior: true }],
      }],
      viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(certificate, {
        aliases: ['example.com'],
      }),
    });

    const zone = route53.HostedZone.fromLookup(this, 'Zone', { domainName: 'example.com' });

    new route53.ARecord(this, 'SiteAliasRecord', {
      zone,
      target: route53.RecordTarget.fromAlias(new targets.CloudFrontTarget(distribution)),
    });
  }
}
  1. Deploy Your Infrastructure:

Use the CDK CLI to deploy your application:

cdk deploy

Cost Optimization

  1. Leverage S3’s Low-Cost Storage Classes:
  • Use storage classes like S3 Standard-IA or S3 One Zone-IA for infrequently accessed data.
  1. Utilize CloudFront Caching:
  • Configure CloudFront to cache static content effectively to reduce data transfer and request costs.
  1. Monitor and Adjust Resources:
  • Use AWS Cost Explorer and CloudWatch to monitor usage and adjust resources accordingly to avoid unnecessary expenses.

Conclusion

By leveraging AWS services like S3, CloudFront, Route 53, and ACM, you can create a robust and cost-effective infrastructure for your static websites. Utilizing Infrastructure-as-Code with AWS CDK enhances the manageability and scalability of your setup. Follow these steps to ensure your static website serves users reliably and efficiently.

Stay Clouding!

Samuel Barden
WRITTEN BY

Samuel Barden

AWS Solutions Architect & Atlassian Developer
I build scalable cloud solutions and develop solutions for Atlassian suite.

Leave a Reply

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