CNAMEs are a neat trick of the domain name system, but are often unused or misunderstood.
Here’s a quick(ish) explanation of what CNAMEs are, how they work, and why you should use them.
CNAMEs are basically an alias of an existing domain. It’s easy to imagine that CNAMEs behave like internal redirects, but they’re much neater.
Aside: CNAME is shorthand for “canonical name”, and refers to the *relationship* that a subdomain – for example – has with the primary or “canonical” domain, rather than the entry itself. So for a CNAME record of
support.cloud.engineyard.com. 6 IN CNAME engineyard.ssl.zendesk.com., the “canonical name” is actually the part right of “CNAME”.
If a domain is set up like so:
ross-air:~ ross$ dig support.cloud.engineyard.com +nostats +nocomments +nocmd ;support.cloud.engineyard.com. IN A support.cloud.engineyard.com. 6 IN CNAME engineyard.ssl.zendesk.com. engineyard.ssl.zendesk.com. 513 IN A 18.104.22.168
Then when a browser visits
support.cloud.engineyard.com, the DNS resolver (usually part of your OS stack) actually sends a standard request for an
A record for
support.cloud.engineyard.com to the nameserver. If this lookup fails, the nameserver will check to see whether the record exists as a
CNAME entry. When it finds it, the nameserver restarts the query using
engineyard.ssl.zendesk.com, which resolves to the IP
The browser sets the
Host header of the request to
support.cloud.engineyard.com (so that the receiving server knows what was originally requested) and continues with the request to the server.
When the server receives this message, it looks up the host it’s been passed and serves up the corresponding configured website.
It’s not just web browsers like Chrome, Firefox, etc that perform this task, tools like
wget, etc will perform the same lookup as part of the request.
CNAMEs are particularly useful when a lot of websites are being hosted at a single IP address. If all the domains hosted at that IP point to a single “gateway” domain, then only that gateway domain needs to point to an IP address, making Domain->IP address portability less of a headache.
If you’re using a web host or platform provider that deals with some of the hassle of server and domain administration for you, this is probably one of the tricks they use to make it possible to handle lots of users without breaking everything when an IP address somewhere needs to change.