I will use a domain name, quizzer.cloud, to demonstrate how to use custom domains for S3 static websites with CloudFormation template:
- Start the template with the template version and a description (optional).
- Define two parameters for accepting the root domain name and the sub-domain name, as follows:
Parameters:
RootDomainName:
Description: Domain name for your website (quizzer.cloud)
Type: String
SubDomainName:
Description: Sub Domain name for your website (www.quizzer.cloud)
Type: String
- Define the root bucket resource, as follows:
Resources:
RootBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Ref RootDomainName
AccessControl: PublicRead
WebsiteConfiguration:
IndexDocument: index.html
ErrorDocument: error.html
- Define a bucket access policy that allows everyone to access the bucket's contents, as follows:
WebsitePublicAccessPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref RootBucket
PolicyDocument:
Statement:
-
Action:
- "s3:GetObject"
Effect: "Allow"
Resource:
Fn::Join:
- ""
-
- "arn:aws:s3:::"
- !Ref RootBucket
- "/*"
Principal: "*"
- Create the redirect bucket, as follows:
WWWBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Ref SubDomainName
AccessControl: BucketOwnerFullControl
WebsiteConfiguration:
RedirectAllRequestsTo:
HostName: !Ref RootDomainName
- Create two A records within the HostedZone, for the root domain and the sub-domain, as follows:
myDNS:
Type: AWS::Route53::RecordSetGroup
Properties:
HostedZoneName: !Sub
- ${DomainName}.
- DomainName: !Ref RootDomainName
Comment: Zone apex alias.
RecordSets:
-
Name: !Ref RootDomainName
Type: A
AliasTarget:
HostedZoneId: 'Z11RGJOFQNVJUP'
DNSName: 's3-website.ap-south-1.amazonaws.com'
-
Name: !Ref SubDomainName
Type: A
AliasTarget:
HostedZoneId: 'Z11RGJOFQNVJUP'
DNSName: 's3-website.ap-south-1.amazonaws.com'
You can also use a CNAME record for sub-domains.
- Add an Outputs section to return the URLs of the root domain and the sub-domain (this is optional):
Outputs:
RootDomainURL:
Value: !Sub
- http://${DomainName}
- DomainName: !Ref RootDomainName
Description: URL for root domain
SubDomainURL:
Value: !Sub
- http://${DomainName}
- DomainName: !Ref SubDomainName
Description: URL for redirect (sub) domain
- Execute the preceding template by passing the parameters, as follows:
aws cloudformation create-stack
--stack-name mys3websitestack
--template-body file://resources/s3-static-website-cf-template.yml
--parameters ParameterKey=RootDomainName,ParameterValue=quizzer.cloud ParameterKey=SubDomainName,ParameterValue=www.quizzer.cloud
--region ap-south-1
--profile admin
You can check the status of the CloudFormation stack creation by using the describe-stacks command.
- Once the stack creation has completed, you will need to upload the index.html and error.html files into the root bucket.
Finally, execute the root domain and the WWW sub-domain in a browser.
You should see the same response from the root bucket in both cases, as follows: