CloudFlare: CDN configuration for AWS S3 website hosting

By | 09/20/2019
 

Need to create a static website hosting using AWS S3 and attach CloudFlare CDN to it.

AWS S3 bucket

Create a new bucket for your website with the same name as it will be used for your site, in this case, it will be cdn.example.com:

Go to the Properties and enable website hosting:

Go to the Permissions, in the Bucket Policy enable full access to this bucket:

 {
    "Version": "2012-10-17",
    "Id": "MyPolicy",
    "Statement": [
        {
            "Sid": "PublicReadForGetBucketObjects",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::cdn.example.com/*"
        }
    ]
}

Let’s check it now.

Create a new file and upload it to the bucket:

[simterm]

$ aws --profile bm-backend s3 cp index.html s3://cdn.example.com
upload: ./index.html to s3://cdn.example.com/index.html

[/simterm]

Open it using bucket’s URL:

[simterm]

$ curl http://cdn.example.com.s3-website.us-east-2.amazonaws.com
TestCDN

[/simterm]

CloudFlare CDN configuration

After registration – go to the Add Site:

CloudFlare supports two types of configuration – full when DNS for a whole domain will be changed thus it will be served totally bu CloudFlare DNS, and partial – when you can configure only one subdomain.

The second one requires to have a Business or Enterprise plan, and while we are waiting for our Enterprise plan to be enabled – let’s use the Full configuration.

Add a domain:

Chose your plan here, for now – Trial, Enterprise will be enabled after email to the support@:

CloudFlare will grab all the records existing for your domain:

And you can create here a new subdomain for your CDN, for example, cdn.example.com with the CNAME record type and set your bucket’s URL:

As the last step – CloudFlare tell us which DNS needs to be set for our domain:

Go to your domain registrar and update its DNS:

Wait a couple of minutes and check:

[simterm]

$ whois example.com | grep Name
Domain Name: example.com
Name Server: cass.ns.cloudflare.com
Name Server: lloyd.ns.cloudflare.com

[/simterm]

Check in the CloudFlare:

And by using, for example, this service – https://checkforcloudflare.selesti.com:

 

SSL

The last thing to do is to update a bit SSL – enable HTTP to HTTPS redirect:

CloudFlare uses its own certificate but you are able to upload an additional one:

Done.