Go Back

Static Website Hosting with AWS S3 using AWS CLI

Updated on 23 September, 2019

AWS

Static website hosting with S3 is one of the cheapest ways to host website which can scale to millions of users. If you follow this commands in this post it will be very easy to setup. You can set it up with a GUI interface on the Amazon website, but we are discussing the commandline method in this blog. If you prefer other method you can see in AWS Docs Static web hosting with S3

The main intent of this post is that readers quickly learn how setup a static website on S3. If you have some basic understanding of AWS it will be beneficial. I will be referring to AWS Docs of relevant topics which we will not be discussing here in detail.

Download, install and configure AWS CLI on your computer

If you don't have it configured on your system please go through the steps in AWS Docs Install and configure AWS CLI

Create bucket

Open commandline and run this command.

$ aws s3 mb s3://my-static-site

Here my-static-site is the name of the new bucket we are creating.

Transfer files to bucket

Now we have to transfer our website files to the new bucket. Navigate to the project directory were the files to be hosted are present and run this command.

$ aws s3 sync . s3://my-static-site

Here we are using the sync command to transfer files from our local folder to S3.

Set up static hosting on the bucket

Now we will setup static hosting on that S3 bucket

$ aws s3 website s3://my-static-site --index-document index.html --error-document error.html

In previous command we are setting up our index document as index.html and error document as error.html. If you have them under different names make changes accordingly.

Change bucket policy for providing public access to the bucket.

Now create policy document with name policy.json in your project directory with following content. Replace "arn:aws:s3:::my-bucket/*" with your bucket resource name.

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

now add that policy to the bucket

$ aws s3api put-bucket-policy --bucket my-static-site --policy file://policy.json

now your website will be available in a url similar to this. http://my-static-site.s3-website.aws-region.amazonaws.com/

Go Back