Redirecting one domain to another with CNAME records.
TypeScriptTo configure a domain redirection using CNAME records, we will define DNS records within a hosted DNS zone. A CNAME record specifies that a domain name is an alias for another domain. This is commonly used to redirect a subdomain to another domain, or to alias a domain to a service where you don't control the DNS (e.g., when using a content delivery network or a hosted blog platform).
The process generally involves two steps:
- Define the alias: Create a CNAME record where the
name
is the domain or subdomain you wish to redirect, and thevalue
is the destination domain to which you want to point. - DNS Zone: Ensure that you have a DNS zone configured where you can place the CNAME record.
For the purposes of this explanation, I'll assume you're using AWS Route 53 as it is a widely-used service and offers comprehensive DNS management capabilities. However, similar principles would apply if you were using a different cloud provider or DNS service.
In our Pulumi program, we will use the
aws.route53.Record
resource, which creates a record in a DNS zone hosted with Route 53. Here's a TypeScript program that accomplishes this:import * as aws from "@pulumi/aws"; // Create a DNS zone if you don't already have one. If you do, you can skip this step. const zone = new aws.route53.Zone("zone", { name: "mydomain.com", // The domain name for this zone. }); // Create a CNAME record for www.mydomain.com that points to myotherdomain.com. const cnameRecord = new aws.route53.Record("cnameRecord", { zoneId: zone.zoneId, // The ID of the hosted zone to contain this record. name: "www.mydomain.com", // The name of the record. type: "CNAME", // The type of the record. ttl: 300, // The Time-To-Live of the record (seconds). records: ["myotherdomain.com"], // The value you are setting for the record. }); // Export the DNS zone name and the CNAME record name export const dnsZoneName = zone.name; export const cnameRecordName = cnameRecord.name;
In this program, we are:
- Importing the
@pulumi/aws
library to interact with AWS resources. - Creating a new Route 53 DNS zone for
mydomain.com
by instantiatingaws.route53.Zone
. - Within that zone, we're creating a new CNAME record
www.mydomain.com
that points tomyotherdomain.com
usingaws.route53.Record
. The record will live as long as the DNS zone exists. - The
ttl
field specifies how long the record is cached by DNS resolvers; a common default value is 300 seconds (5 minutes). - Finally, we're exporting the name of the DNS zone and the CNAME record. This allows you to use the values in the Pulumi stack, or reference them from other programs or stacks.
Please be aware that it might take some time for DNS changes to propagate globally due to caching and the distributed nature of DNS.
- Define the alias: Create a CNAME record where the