Pointing multiple subdomains to a single CloudFront distribution
In slack, each team is issued a subdomain. For example, if I create a Slack team, it would be k5trismegistus.slack.com.
I wondered how to create a web service that can provide services with a subdomain for each user or group like this, so I experimented with it.
Assumptions
- Infrastructure is running on AWS
- The application front-end is delivered by CloudFront.
- The service will be delivered by *.app.example.com. The application will use the string in * (replace example.com with your domain as appropriate).
- Example.com is already registered in Route53.
Application
For the application side, we only need to be able to reach with the subdomain properly and get the subdomain information, so we created an experimental application that simply displays the subdomain in Nuxt.js and put it in S3.
If the subdomain is the lowest-level, i.e. a.b.example.com, this service just displays a.
https://github.com/k5trismegistus/nuxt_subdomain_test/blob/master/pages/index.vue
By the way, hosting a Nuxt.js SPA in S3 and delivering it via CloudFront requires a bit of work. (It is necessary to rewrite the request to /path to a request to /path/index.html with CloudFront Functions or else.)
Route53 configuration (1)
Create a hosted zone for app.example.com in Route53. Then create an NS record for app.example.com in the hosted zone of example.com.
Reference
https://aws.amazon.com/premiumsupport/knowledge-center/create-subdomain-route-53/?nc1=h_ls
Issue the certificate.
Issue a certificate for *.app.example.com from ACM.
If you want to verify the certificate with DNS, use the aforementioned
Then, create an NS record for app.example.com in the hosted zone of example.com.
You may also need to do this. Don’t forget to do this too.
Configure CloudFront
Create a CloudFront distribution, specify the application (S3 bucket in the case of this example) as the origin, attach the certificate issued earlier, and write *.app.example.com in the CNAME field. To specify the CNAME, you need to have a certificate issued for the corresponding domain.
Route53 configuration
Then, in the hosted zone of app.example.com, create an alias record for the CloudFront distribution that you just created. If you don’t set up the CNAME settings first, it won’t appear in the list of candidates.
In this case, the record name should be *.app.example.com.
Reference
https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-values-alias.html
Done.
It’s done.