Posts: CDK Subdomain Hosted Zone

Configuring a subdomain hosted zone to support second-level subdomains

Today I needed to add a second-level subdomain in Route53. While the documentation exists, a clear block of code did not. In order to support more subdomains you must:

  1. Create a new hosted zone for the first-level subdomain (sub1.example.com)
  2. Note the nameservers in the new hosted zone
  3. Add an NS record to the root domain hosted zone (example.com) with a name of sub1 and the nameservers from the step above
  4. Add the new A or CNAME records to the new hosted zone to create a second-level subdomain (sub2.sub1.example.com)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const rootDomain = 'example.com';
const subDomain = 'sub1';

const rootZone = HostedZone.fromLookup(this, 'RootHostedZone', {
  domainName: rootDomain,
}) ;

const subZone = new HostedZone(this, 'SubHostedZone', {
  zoneName: `${subDomain}.${rootDomain}`,
});

new NsRecord(this, 'SubdomainNS', {
  zone: rootZone,
  recordName: subDomain,
  values: subZone.hostedZoneNameServers!,
});

// Add your A or CNAME records to subZone to create sub2.sub1.example.com

Skipping the nameserver records will cause the subdomains to fail to resolve, and if you are deploying a certificate, validation will never complete!