12. Subdomains and Running Many Apps on One Server
“One address, many doors. The name on the envelope picks the door.”
The story: the box that grew a second app
Section titled “The story: the box that grew a second app”It is 11:40 on a Thursday night. You have three things on one small VPS: the marketing site for the box-office data project, the research SaaS, and the little team-status tool your eight people open every morning. Everything answers on the same public IP. Everything works. Then someone on the team asks whether there is a staging copy they can break without breaking production, and the honest answer is “sort of, on port 8080, if you remember the port.”
That answer should make you wince a little, because you have been here before. You know how to make nginx answer for a name. You have typed server_name into a config and watched it work. What you may not know is why one IP can serve three apps at all, what the name is doing inside the request, and why the thing that looks like a little prefix in your browser is, underneath, a label in a database that every resolver in the world reads.
This chapter is about that label. A subdomain is the cheapest tool you have for splitting one thing into many. Used well, it lets one server host many apps cleanly. Used carelessly, it lets a forgotten staging copy read the cookies that keep your users logged in. The difference lives in details most tutorials skip: cookie scopes, the gap between an origin and a site, a list maintained in public by volunteers that quietly decides what counts as “your” domain, and a class of bug where a DNS record outlives the thing it points to.
Hold the chai-stall test in mind while you read. The question is never “does it work when I type the URL?” It is “does it still behave when somebody else types a different URL, or when one piece of the system goes wrong?” Every idea here gets tested against that question.
Priya’s ₹12,000 phone, on a Pune tower at rush hour, is still the best test rig for a cookie bug. Slow networks find the problems that your laptop on office wifi politely hides.
What a subdomain is: a label you were always allowed to add
Section titled “What a subdomain is: a label you were always allowed to add”Start with a name you type all day. www.example.com looks like an address, but it is a name. Somewhere in DNS, the zone for example.com holds a record that says, in effect, “the label www under me points at this address.” The www is just a label. Nobody sells it to you. You write it into the zone, and the name exists.
That is the whole trick. A subdomain is a label stuck on the front of a domain you already own. app.pipeslab.in is pipeslab.in with one more label in front. So are api, staging, admin, and status. Each one costs a record, a few seconds of typing, and nothing at the registrar. You do not buy app.pipeslab.in. You never could, and you never needed to.
Read a name from the right, because that is the order the resolver walks it. in is a top-level branch. pipeslab hangs off it, and app hangs off that. Figure 12.1 draws the tree. The city directory from Chapter 10 has a drawer for each top-level domain, and your domain gets one folder in that drawer, with one tab for every app.
A subdomain is a fact about DNS, not about your server. The record only says where the name points. The machine at that address still has to decide what to do with a request that asks for app.pipeslab.in. That decision is the subject of the routing section below, and it is where most of the real work lives.
One piece of vocabulary to keep straight. The registered domain is the part you paid for, such as pipeslab.in. Chapter 11 covers how you get one. Everything to its left is a subdomain you can create whenever you like. Later in this chapter the registered domain matters a great deal, because browsers draw their security boundaries around it.
Subdomain or subdirectory: the call you will make over and over
Section titled “Subdomain or subdirectory: the call you will make over and over”You have two ways to put a second thing on your site. app.pipeslab.in is a subdomain. pipeslab.in/app is a subdirectory, a path under the same name. Both work, and very large companies use both. People often treat the choice as taste. It is not taste. It decides what the browser lets you share, who can ship what, and how far one mistake spreads.
Here is what actually changes when you pick one over the other.
Cookies. A cookie is scoped to a host. By default, a cookie set by app.pipeslab.in goes only to app.pipeslab.in. Subdirectories share a host, so pipeslab.in/app and pipeslab.in/blog see the same cookies. That is useful when the two are one product and a leak when they are not.
CORS. Cross-origin requests are the ones where scheme, host, or port differ. A page on app.pipeslab.in calling api.pipeslab.in is cross-origin, so your API has to opt in with CORS headers. A page calling /api on its own host is same-origin, and CORS never comes into it. If your frontend and API are tightly coupled, that is a real point for paths.
Isolation. A subdomain can be a separate app with its own process, certificate, deploy, and failures. A subdirectory usually lives in the same server config. A typo in the nginx file that serves your blog can take down the app beside it, because they share one file.
Deployment independence. A subdomain ships on its own schedule. A subdirectory tends to ride along with whatever else is in the repo.
SEO. Search engines have said both work, and what they say shifts over the years. In practice, many people who look after search rankings still prefer subdirectories for content, because the authority a site earns tends to pool on one host. Treat that as a tilt, not a law.
My recommendation, without hedging: use a subdomain for a separate app, meaning something with its own login, its own database, or its own release train. Use a subdirectory for content of one site, such as a blog, docs, or a pricing page. If you cannot decide, ask the two questions that matter. Does this thing need its own cookies? Does it need its own deploy? If either answer is yes, it is a subdomain.
Wildcard DNS and wildcard certificates
Section titled “Wildcard DNS and wildcard certificates”A wildcard record is one line in your zone that says: any name under pipeslab.in that has no record of its own gets this answer. *.pipeslab.in makes anything.pipeslab.in resolve, including the typo, the experiment you forgot, and the customer who signed up yesterday. Chapter 10 covers the precedence rules. An explicit record always beats the wildcard for that exact name.
Two limits catch people out. A wildcard covers one label only. *.pipeslab.in matches app.pipeslab.in but not a.b.pipeslab.in. And it never matches the apex, so pipeslab.in itself needs its own record.
A wildcard certificate follows the same rules. A certificate for *.pipeslab.in covers one label, so you list the apex as a second name on the same certificate, or your bare domain gets a warning. The certificate authority cannot make a web request to a name that could be any of thousands, so it checks you with DNS-01: you prove control by publishing a TXT record. Chapter 9 walks through that challenge. Wildcards and DNS-01 come as a pair.
My opinion on the trade: a wildcard certificate is convenient, with one key, one renewal, and every name covered. It is also one key that can impersonate every name under the domain. If that key leaks from a staging box, your admin panel is exposed too. Use per-name certificates for the front doors that matter most, such as app, api, and admin. Use a wildcard only where the names are many and disposable, such as preview environments or per-tenant names.
Per-tenant subdomains: one app, many customers
Section titled “Per-tenant subdomains: one app, many customers”Software-as-a-service products often give each customer a name, such as acme.yourapp.in and globex.yourapp.in. The mechanics match the wildcard above: one wildcard record, one wildcard certificate, and one application that reads the Host header and loads the right tenant. Each customer gets an address that feels like their own office, and you run one front door.
The catch is trust. Your customers’ names sit under your domain, so anything one tenant controls sits next to every other tenant. If your cookies are scoped to yourapp.in, one tenant’s content shares a cookie jar with all the others. The fix lives in the Public Suffix List section below, and it is not optional. Hold that thought.
Routing by the Host header: one address, many offices
Section titled “Routing by the Host header: one address, many offices”Here is the trick that makes all of this cheap. Every name in this chapter can point at the same IP address. When a browser asks for app.pipeslab.in, DNS answers 203.0.113.10. When it asks for api.pipeslab.in, DNS gives the same number. The browser connects to that one address and sends a request. Inside the request is a line that says, in effect, “I wanted app.pipeslab.in.” That line is the Host header, and it is the only thing the server needs to tell the two visits apart.
This is the receptionist’s whole job. The reverse proxy from Chapter 8 reads the Host header, matches it against its list of names, and walks the visitor to the right office at the back. In nginx that list is the server_name directive. In Caddy it is the address at the top of a site block. Same idea, different spelling.
Two consequences matter. First, the proxy only routes names it knows. A request for zzz.pipeslab.in with no matching block lands on a default site or gets refused, depending on how you set it up. Second, the Host header comes from the client. A visitor can send whatever Host they like. The proxy may trust it for routing, which is fine. No app should trust it for identity. The receptionist reads the name on the envelope, and that does not prove who wrote the letter.
Cookies and the Domain attribute
Section titled “Cookies and the Domain attribute”A cookie is a small note the server hands the browser, and the browser hands it back on later requests. It is how a login survives a page reload. The question is which requests get the note back, and two attributes decide that.
By default a cookie is host-only. A cookie set by app.pipeslab.in goes back only to app.pipeslab.in. Not to api.pipeslab.in, and not to the bare domain. That is the safe default.
Set Domain=pipeslab.in and the cookie widens. The browser now sends it to pipeslab.in and to every name beneath it, including names you have not created yet. That is how one login can travel across your apps. It is also how one weak app becomes a problem for all of them. Browsers refuse a Domain that does not cover the host setting it, so app.pipeslab.in can set a cookie for pipeslab.in but not for example.com.
Figure 12.3 shows both scopes.
Here is the uncomfortable part. A wide cookie is a promise about the least trustworthy app that will ever live under the domain, not the most trustworthy one. Your marketing site runs a plugin you forgot about. Staging holds a half-finished login page. Tomorrow a tenant will claim a subdomain and paste in a script. Each of them can read any cookie that is not HttpOnly, and each of them gets sent the wide cookie. An attacker who takes over staging can set a cookie for pipeslab.in that overwrites your real session cookie in the browser. Security people call this cookie tossing, and it is not exotic.
Two flags help. Secure sends the cookie only over HTTPS. HttpOnly hides it from page scripts. Neither stops a sibling from sending a request with the cookie attached. The __Host- name prefix is stronger. A cookie with that prefix must be Secure, must have Path=/, and must have no Domain at all, so the browser keeps it on one name. My advice: use __Host- for session cookies on every app, and reserve a parent-scoped cookie for the few things you truly want shared.
The Glue Book covers cookies in general in its storage chapter and its security chapter.
Same-site, eTLD+1 and the Public Suffix List
Section titled “Same-site, eTLD+1 and the Public Suffix List”Here is the trap that catches smart people. “Same origin” and “same site” sound like synonyms. They are not, and the browser draws its two lines in different places.
An origin is the scheme, host and port together. https://app.pipeslab.in and https://api.pipeslab.in are different origins, and CORS cares about that line.
A site is coarser. It is the scheme plus the registrable domain, the name you actually bought. app. and api. under pipeslab.in are one site, and cookies’ SameSite rules and most browser isolation features care about that line.
The registrable domain has a formal name, eTLD+1. Take the effective top-level domain, the suffix the public registers under (in, com, co.uk), and add one label. For api.pipeslab.in that gives pipeslab.in.
Now the twist. Some suffixes are places where strangers rent names. github.io is one: you.github.io and them.github.io each sit one label below it. If the browser treated github.io as one owner’s domain, a page on one could set cookies the other could read. So the browser keeps a list of places where the public registers names, the Public Suffix List, a community-maintained file of several thousand entries.
The result is that you.github.io and them.github.io are different sites, and a page cannot set a cookie with Domain=github.io, because the browser refuses to scope a cookie to a public suffix. Your pipeslab.in is not on the list, so Domain=pipeslab.in works. That is the whole reason the list exists.
Subdomain takeover: the name that points at nothing
Section titled “Subdomain takeover: the name that points at nothing”This story is a composite, stitched from patterns that repeat in public write-ups. A team launches a campaign page at promo.pipeslab.in and points a CNAME at a storage bucket the vendor created. The campaign ends. Somebody deletes the bucket. Nobody deletes the record. The DNS still says promo.pipeslab.in belongs to a name that no longer exists.
On shared platforms, resource names are first come, first served. An attacker creates a bucket with that exact name and serves what they like. Your subdomain is now theirs, and your users see your name in the address bar. If the attacker can pass the certificate challenge for the name, which they can when they control what it serves, they get the padlock too.
It is common in big companies because the conditions are built in. Many teams, many cloud accounts, resources created by one project and deleted by another, and DNS owned by a central team that never hears about the deletion. The record outlives the work, and nobody’s job is to look at it.
What does the attacker get? A phishing page on a name your users trust. Any cookie scoped to pipeslab.in, since script on any sibling can read it. And any API whose CORS list allows *.pipeslab.in. A host-only cookie on app. is out of reach from promo., one more reason to prefer them.
Prevention comes in four moves:
- Delete the record before the resource. A record with no target is an error. A record pointing at a free name is a takeover.
- Inventory every record that points at a provider. CNAMEs to buckets, platform hosts, static hosts and CDNs are the ones to list.
- Check for dangling records on a schedule. A script that resolves each CNAME and flags targets answering with a “no such resource” page catches most of them.
- Stop scoping cookies to the parent. Use host-only cookies or
__Host-names, as in the cookie section above.
The applied domain plan
Section titled “The applied domain plan”Here is the plan I would hand a new engineer on day one for your projects. Each name is its own deployment with its own cookies and release rhythm. The last two rows need an extra lock.
| Host | What lives there | Why it is its own name | Who reaches it |
|---|---|---|---|
pipeslab.in, www. |
Marketing site | Static and cacheable; www redirects to the apex |
Everyone |
app.pipeslab.in |
The product (Next.js) | Users log in here and own the session cookie | Users |
api.pipeslab.in |
JSON API for the app and any mobile client | Its own CORS and rate-limit rules | Authenticated callers |
admin.pipeslab.in |
Internal admin tools | Isolated cookies, and a clean place for Access | Your team (Ch 17) |
staging.pipeslab.in |
Pre-release copy | Its own database and its own Access policy | Your team (Ch 17) |
status.pipeslab.in |
Status page, hosted by a third party | The provider owns that name’s life | Everyone |
Two rules sit under the table. The apex cannot be a CNAME (Ch 10), so it takes A or AAAA records, or the flattening option your DNS host offers. And status. is the takeover risk in this plan: when you cancel that account, remove its CNAME in the same change.
Read the tree top down. Three names are plain public sites or APIs. Two are locked by you: admin. and staging. should never be reachable by a stranger, and Ch 17 puts Access in front of them so the lock sits outside the app. status. is public too, but it points at someone else’s service, so it is the name to watch.
Your dance-academy branches, say Pune and Mumbai, belong under paths: /pune and /mumbai. They share one login, one database and one release, so a path keeps one cookie, one certificate and one deployment. Give a branch a subdomain only when it needs its own sign-in, billing or deploy.
Mail has its own records (MX, SPF, DKIM, DMARC), covered in Ch 13. Keep mail hosts off the names that serve web pages.
The lab: three names, one server, one cookie
Section titled “The lab: three names, one server, one cookie”Goal. Give the lab VPS three names, app., api. and staging. under pipeslab.in, route each to its own app, then prove that a Domain-scoped cookie travels between the names and a host-only cookie does not.
Conceptual steps.
- Point the three names at the lab’s public address, with three records or one wildcard. Write down which, and what the wildcard also catches.
- Run
hello-pipesthree times on local ports 3001, 3002 and 3003, one per name, each listening only on loopback. - Put one reverse proxy in front. It reads the Host header and forwards to the matching port. An unknown Host gets refused.
- Give each name a certificate: three per-name, or one wildcard via DNS-01 (Ch 9). Say which and why.
- Set a cookie from
app.with Domain=pipeslab.in. Check what arrives atapi.andstaging.. - Set a second cookie from
app.with no Domain. Check where it goes.
How you’ll know it worked. Each name prints its own Host. An invented Host is refused. The shared cookie reaches api. and staging., and the host-only cookie reaches only app.. If the shared cookie is missing, check the Domain value first.
What you now know
Section titled “What you now know”- A subdomain is a free DNS label. The real decision is cookies, origins and who owns the deploy.
- Subdomains suit separate apps. Subdirectories suit one site’s content.
- A wildcard matches one label, and a wildcard record is not a wildcard certificate.
- One IP and one Host-aware proxy can serve many apps, but the Host header is only a claim.
- Domain widens a cookie to every name under the parent, and widens the blast radius with it.
- The Public Suffix List decides what counts as a site.
- A dangling CNAME is a name someone else can claim. Delete the record first, and check on a schedule.
You can now look at a list of names and say which are apps, which are content, which are locked, and which one forgotten account could put at risk. That is most of the job. Well done.
Self-quiz
Section titled “Self-quiz”1. Why does a subdirectory share cookies with its site, but a subdomain does not?
Cookies are scoped to a host, and the path does not separate them. site.in/app and site.in/blog see the same cookies. app.site.in is a different host, so its host-only cookies stay apart unless Domain widens them.
2. Why can you.github.io and them.github.io not share cookies?
The Public Suffix List marks github.io as a public suffix, like a top-level domain. Each user’s site is its own eTLD+1, so browsers treat them as different sites.
3. Does *.pipeslab.in cover pipeslab.in or a.b.pipeslab.in?
Neither. A wildcard matches exactly one label. The apex needs its own record, and two-level names need their own wildcard.
4. What goes first when you retire a service that a CNAME points at?
The DNS record. Delete the CNAME before the resource, so the name never points at an unclaimed target.
5. Why is Domain=pipeslab.in riskier than a host-only cookie?
Every name under the parent can read and overwrite that cookie, including a sibling you have not hardened. A host-only cookie reaches only the host that set it.
Exercises
Section titled “Exercises”Warm-up 1. Pick the shape. Your team wants a status page, a docs site for one product, and a tenant dashboard for a second product. Subdomain or subdirectory for each, and why?
Answer
Status page and tenant dashboard: subdomains, since they are separate apps with their own deploys or logins. Docs: a subdirectory if it is one product’s content, a subdomain if another team ships it.
Warm-up 2. Wildcard reach. Which of these does *.pipeslab.in cover: app.pipeslab.in, pipeslab.in, a.b.pipeslab.in?
Answer
Only app.pipeslab.in. The apex and two-level names are outside a single-label wildcard.
Warm-up 3. Three defences. Name three habits that prevent subdomain takeover.
Answer
Remove DNS before the resource. Inventory every record that points at a provider. Run a scheduled check for dangling targets. Avoid parent-scoped cookies as a backstop.
Lab 4. Add a fourth name. Give docs.pipeslab.in its own app on port 3004 and prove the proxy routes it.
Answer
Hint: add the record, add a proxy block for the new Host, then request the lab with that Host header using curl. Model solution: the response prints the docs Host, and the proxy config gains one block without changing the others.
Lab 5. Prove the cookie scope. Set a Domain=pipeslab.in cookie at app., then show it at api. and staging.. Show a host-only cookie at app. never reaches api..
Answer
Hint: hello-pipes prints the Cookie header it receives, and a cookie jar file keeps the cookies between requests. Model solution: the shared cookie appears at all three names, and the host-only cookie appears only at app..
Lab 6. Choose a certificate plan. For the names you run, decide per-name or wildcard, and justify it in two sentences.
Answer
Hint: count the certificates, note which names need DNS-01, and say where the API token lives. Model solution: one wildcard for the names you run, since one DNS-01 token covers them. The third-party status name keeps the certificate its provider issues.
Staff 7. Per-tenant SaaS. Your research SaaS gives each customer customer.pipeslab.in. Design the DNS, certificate, routing and cookie choices in one paragraph.
Answer
Model answer: one wildcard record and one wildcard certificate via DNS-01. The proxy routes every Host to one app, which looks up the tenant from the Host and rejects unknown ones. Cookies stay host-only, so a session never reaches a sibling, and the app never sets Domain. Custom domains need per-name certificates, issued on demand and rate-limited.
Staff 8. Retire a vendor safely. A vendor you are cancelling is the target of three of your CNAMEs. Write the steps in order.
Answer
Model answer: find all three records. Remove or repoint each one before cancelling. Confirm the names no longer resolve to the vendor. Cancel the account. Check for parent-scoped cookies that those names could have read, and remove those cookies too.
Book 2 of a series. Book 1: The Glue.