Migrate from subdomain to path-based routing
Example migration: stag.playout.castis.io → stg.playtelly.castis.io/playout
Overview¶
This guide documents migrating a multi-app setup from one subdomain per app to one shared hostname with path-based routing (/playout, /tellyboard, etc.). This lets multiple frontend apps share a single hostname while staying fully isolated from each other.
Architecture¶
Internet
│
▼
Public APISIX Gateway (edge cluster)
│ ApisixRoute: catch-all "/*" for the shared hostname
│ → forwards everything, no per-app path logic here
▼
Tailscale tunnel
│
▼
Private APISIX Gateway (internal cluster)
│ HTTPRoute per app: matches /playout, /tellyboard, etc.
│ → forwards to the matching backend Service
▼
App pod (nginx serving the built SPA)
Division of responsibility:
- Public gateway — one dumb catch-all route, no app-specific knowledge.
- Private gateway — one HTTPRoute per app, each owning its own path prefix.
- Each app — fully self-contained under its own prefix (build config + router + nginx all agree on the same path).
Mental model: which config affects which part of the request lifecycle¶
A request for a client-side route (e.g. /playout/dashboard, which isn't a real file) passes through several distinct stages, each controlled by a different piece of config. Understanding which config governs which stage is the key to debugging this kind of setup.
┌─────────────────────────────────────────────────────────────────────┐
│ 1. GATEWAY ROUTING (HTTPRoute / ApisixRoute) │
│ Decides: which backend Service does this hostname+path go to? │
│ Does NOT care about file existence, SPA routes, or asset paths. │
└──────────────────────────────┬──────────────────────────────────────┘
▼
┌─────────────────────────────────────────────────────────────────────┐
│ 2. NGINX (location + try_files) │
│ Decides: is there a real file on disk for this exact path? │
│ If yes → serve it directly (e.g. static/index-abc.js). │
│ If no → fall back to serving index.html (the SPA "shell"). │
│ Server-side logic ends here — nginx has no idea what "/dashboard"│
│ means as an application concept. │
└──────────────────────────────┬──────────────────────────────────────┘
▼
┌─────────────────────────────────────────────────────────────────────┐
│ 3. index.html → loads the JS bundle │
│ Contains only a <script src="/playout/static/index-abc.js"> │
│ reference — this exact reference is baked in by Vite's `base` │
│ setting at build time. No app logic lives in this file itself. │
└──────────────────────────────┬──────────────────────────────────────┘
▼
┌─────────────────────────────────────────────────────────────────────┐
│ 4. BROWSER executes the JS bundle │
│ React + React Router + all app components boot up client-side. │
│ React Router reads window.location.pathname (e.g. │
│ "/playout/dashboard"), strips the `basename` prefix you │
│ configured on <Router>, matches what's left ("/dashboard") │
│ against your <Route path="/dashboard"> definitions, and renders │
│ the matching component — entirely in the browser, no further │
│ server request needed for the routing decision itself. │
└─────────────────────────────────────────────────────────────────────┘
Table: config → what it actually controls¶
| Config | Where it lives | What it controls | What breaks if misconfigured |
|---|---|---|---|
HTTPRoute / ApisixRoute |
Gateway YAML | Which backend Service a hostname+path prefix is forwarded to | Request never reaches the pod at all — 404 from the gateway itself (check Server header + response body to tell this apart from an nginx 404) |
vite.config.js → base |
Build config | The exact asset URLs (<script src="...">) baked into index.html and JS chunks at build time |
Browser requests assets at the wrong path (e.g. bare /static/... instead of /playout/static/...) → 404s on JS/CSS, blank page |
Dockerfile → COPY --from=build /app/dist <path> |
Build/image | Where the built files physically land inside the container | If this path doesn't match what base told the browser to request, files exist but at the wrong location → 404s even though ls shows the file |
nginx location + try_files |
nginx config | Whether a request matches a real file, and what to serve as a fallback for unmatched (client-side route) requests | Wrong fallback path (missing prefix) → try_files's internal redirect re-matches locations and finds nothing → 404, even though index.html exists on disk |
React Router basename |
App code (<Router basename="...">) |
How the in-browser router interprets the current URL and generates links/navigations | Without it, the router expects routes at root; visiting /playout/dashboard won't match any <Route>, and <Link>/navigate() calls generate root-relative URLs that lose the prefix |
Raw window.location.href = ... |
App code, anywhere | Full browser navigation, completely bypassing React Router | basename has zero effect here — every one of these call sites needs the prefix added manually (typically via import.meta.env.BASE_URL), or the user gets bounced to the wrong (unprefixed) URL — this is the auth-redirect and session-expiry bug pattern |
Why a 404 can come from two very different places¶
A 404 response with Server: APISIX/x.x.x in the header does not necessarily mean APISIX itself failed to route the request — APISIX's Server header persists even when it's just passing through a 404 generated by the app's own nginx further downstream. To tell them apart, look at the response body:
- APISIX's own "no route matched" 404 is typically a plain JSON error.
- nginx's own default 404 page looks like <html>...<hr><center>nginx/x.x.x</center></html> — if you see this, the request did reach the pod; the problem is inside nginx's location/try_files config, not the gateway.
This distinction is the fastest way to know which of the two completely different debugging paths (gateway config vs. nginx config) to go down.
Why a build-time base path (not just gateway rewriting)¶
A common mistake: assuming path-based routing is only a gateway/nginx concern. It's not — three layers must all agree on the same prefix, or you get broken assets, broken deep links, and broken redirects:
| Layer | What it controls | Config |
|---|---|---|
| Build tool (Vite) | Asset URLs baked into index.html/JS bundle |
base in vite.config.js |
| Client-side router | In-app navigation (Link, navigate()) |
basename on <Router> |
| Web server (nginx) | Which physical files/paths get served | location blocks |
The gateway (ApisixRoute/HTTPRoute) only decides which backend a request goes to based on path prefix — it does not, and should not, need to know anything about the app's internal structure.
Rule of thumb: whatever prefix you choose at the gateway, the app must be built/configured knowing it lives at that same prefix — end to end.
Step 1 — Public gateway: single catch-all route¶
No per-app path logic needed here. One route forwards everything to the private gateway over Tailscale.
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
name: staging-public
namespace: staging
spec:
upstreams:
- name: private-gateway-upstream
nodes:
- host: <tailscale-ip-of-private-gateway>
port: 80
weight: 100
http:
- name: staging-public
match:
hosts:
- stg.example.io
paths:
- "/*"
upstreams:
- name: private-gateway-upstream
weight: 100
plugins:
- name: redirect
enable: true
config:
http_to_https: true
- name: proxy-rewrite
enable: true
config:
headers:
set:
X-Forwarded-Proto: "https"
X-Forwarded-Host: "stg.example.io"
Common pitfall:
spec.http[].upstreamsis only a weighted reference — you also need a top-levelspec.upstreamsblock defining the actual target (nodes), or the route matches but has nowhere to send traffic (silently manifests as a 404, not a 502).
Companion ApisixUpstream (if using externalNodes for a Tailscale IP)¶
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
name: private-gateway-upstream
namespace: staging
spec:
externalNodes:
- type: Domain
name: "<NUC_A_TAILSCALE_IP>"
port: 80
weight: 1
scheme: http
loadbalancer:
type: roundrobin
Step 2 — Private gateway: one HTTPRoute per app¶
There are two ways to shape this, depending on whether the app's internal API/asset paths are namespaced under its own prefix or left at root. Prefer Option A — it's what fully eliminates cross-app path collisions.
Option A (recommended): everything namespaced under the app's own prefix¶
If the app is configured so all its requests — page, static assets, API calls, uploads — go through /playout/... (e.g. /playout/api/..., /playout/assets/..., /playout/files/...), the gateway only needs one rule:
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: playout-route
namespace: staging
spec:
parentRefs:
- name: apisix-gateway
namespace: apisix
hostnames:
- stg.example.io
rules:
- matches:
- path:
type: PathPrefix
value: /playout
backendRefs:
- name: playout-service
port: 80
Everything under /playout/* is a single prefix match — the gateway doesn't need to know about the app's internal sub-paths at all, since nginx handles that split internally (see Step 4).
This is the pattern to reach for once an app's build/router/nginx are fully self-contained under its own prefix — it also fully removes the cross-app collision risk described below, since a second app (/tellyboard) can freely have its own /tellyboard/api, /tellyboard/assets, etc. without ever touching /playout's namespace.
Option B: app's internal paths stay at root (not namespaced)¶
If the app's assets/API calls are still root-relative (/static/..., /api/..., not /playout/static/...), the gateway needs a separate rule per root path the app actually uses:
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: playout-route
namespace: staging
spec:
parentRefs:
- name: apisix-gateway
namespace: apisix
hostnames:
- stg.example.io
rules:
- matches:
- path:
type: PathPrefix
value: /playout
backendRefs:
- name: playout-service
port: 80
- matches:
- path:
type: PathPrefix
value: /api
backendRefs:
- name: playout-service
port: 80
- matches:
- path:
type: PathPrefix
value: /assets
backendRefs:
- name: playout-service
port: 80
- matches:
- path:
type: PathPrefix
value: /files
backendRefs:
- name: playout-service
port: 80
Collision risk with Option B:
/api,/assets,/filesare root-level, shared-namespace paths. The moment a second app on the same hostname also needs root-level/apior/assetspointed at a different backend, there's no way to route around the collision — both apps can't own the same root path on one host. This is the main reason to migrate to Option A once you're adding a second app.
Repeat whichever option you choose — one new HTTPRoute, its own prefix, its own backend Service — for each additional app (/tellyboard, etc.).
Verifying the route actually bound¶
Checkstatus.parents[].conditions — both Accepted and ResolvedRefs should be True.
Check spec.listeners[].hostname (if restricted) actually matches/allows the new hostname, and allowedRoutes.namespaces permits your app's namespace.
Step 3 — Vite build config: set base¶
// vite.config.js
export default defineConfig({
base: '/playout/',
plugins: [ /* ... */ ],
build: {
assetsDir: 'static', // or 'assets' — whatever the project already uses
},
// ...
})
This is the single most important change. It makes the built index.html reference /playout/static/index-abc123.js instead of /static/index-abc123.js — so asset URLs and the app's actual mount point agree.
assetsDirandbaseare different settings —assetsDironly names the output subfolder,basecontrols the URL prefix baked into the HTML. Both are needed; changing only one doesn't fix the mismatch.
Dockerfile — copy build output into a matching subfolder¶
With base: '/playout/' set, this now correctly lines up: the browser requests /playout/static/..., and the file physically lives at /usr/share/nginx/html/playout/static/....
Step 4 — nginx: serve the app under its prefix¶
Option A (recommended): all internal paths namespaced under /playout/¶
location /playout {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /playout/index.html;
}
location /playout/api/ {
proxy_pass http://coreapi-service.namespace.svc.cluster.local:3000/api/v1/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /playout/assets/ {
proxy_pass http://coreapi-service.namespace.svc.cluster.local:3000/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_buffering off;
proxy_request_buffering off;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
proxy_method $request_method;
}
location /playout/files/ {
proxy_pass http://tusd.namespace.svc.cluster.local:8080/files/;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-Proto $real_proto;
proxy_request_buffering off;
proxy_buffering off;
client_max_body_size 500M;
add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Methods "POST,GET,HEAD,PATCH,DELETE,OPTIONS" always;
add_header Access-Control-Allow-Headers * always;
add_header Access-Control-Expose-Headers * always;
if ($request_method = OPTIONS) {
return 204;
}
}
nginx matches the most specific location prefix, so location /playout/api/ correctly takes priority over the broader location /playout for requests under that sub-path — order in the file doesn't matter for prefix matching (unlike HTTPRoute, nginx always picks the longest match automatically).
This is what pairs with Option A in Step 2 — a single HTTPRoute rule for /playout covers all of this, since nginx does the internal split.
Option B: app's internal paths stay at root¶
location /playout {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /playout/index.html;
}
try_filesfallback trap: falling back to/index.html(without the prefix) triggers an internal redirect that nginx re-matches against alllocationblocks from scratch. If no block matches the bare fallback path, you get a 404 even though the file exists on disk. Always fall back to the prefixed path (/playout/index.html), matching where the file actually is.
If /api, /assets, /files remain shared, root-level proxies (not app-specific), leave them as-is:
location /api/ {
proxy_pass http://coreapi-service.namespace.svc.cluster.local:3000/api/v1/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
This pairs with Option B in Step 2 — the HTTPRoute needs a separate rule per root path, and this only works safely if no other app on the same hostname needs those same root paths for a different backend.
Step 5 — Client-side router: set basename¶
import.meta.env.BASE_URL is a Vite built-in — automatically equal to whatever base is set to (/playout/). Using it instead of hardcoding keeps the router in sync with the build config automatically.
With basename set, all existing <Route path="/dashboard">-style paths and navigate('/dashboard') calls continue to work unmodified — React Router transparently applies the prefix everywhere.
Step 6 — Audit raw browser navigation (window.location.href)¶
basename only affects React Router's own navigation. Anything using window.location.href, .replace(), or .assign() directly bypasses React Router entirely and needs the prefix applied manually.
For each hit pointing at a root-relative path, fix it to use the base path:
Common places this bug hides:
- Session-expiry / 401 handlers (e.g. apiFetch wrappers) — redirect users to root instead of the app's own prefix.
- Auth redirect helpers — building a redirect_uri to send to an external identity provider (e.g. window.location.origin + "/" instead of window.location.origin + import.meta.env.BASE_URL).
- Dangling references to routes that don't actually exist (e.g. a hardcoded /auth path with no matching <Route>) — worth confirming the target route is real before just fixing the prefix.
External identity providers (SSO/OAuth-style flows) return the user to whatever
redirect_uriyour app sent them — if that URL never included the path prefix to begin with, the provider isn't "stripping" it; the prefix was simply never sent. Fix this at the source (where the redirect URL is constructed before leaving your app), not at the destination that reads the returned value.
Step 7 — CORS and cookies: what does not need path changes¶
- CORS operates at the origin level only (scheme + host + port) — it has no concept of URL paths. An allowlist entry for
https://stg.example.iocovers every path under it; no change needed for path-based routing. - Cookies can have a
Pathattribute that does restrict which requests they're sent with. If a session cookie is scoped toPath=/playout, it won't be sent on root-level/api/...requests — check this if auth calls fail after migration. PreferPath=/(or omit it) so cookies apply across the whole domain regardless of which app set them.
Verification checklist¶
Test in this order to isolate exactly where any remaining break lives:
# 1. Confirm the private gateway resolves the route with a direct hit (bypasses public/tailscale)
curl -v -H "Host: stg.example.io" http://<private-gateway-tailscale-ip>/playout
# 2. Confirm static assets resolve at the new prefix
curl -v -H "Host: stg.example.io" http://<private-gateway-tailscale-ip>/playout/static/<actual-file>.js
# 3. Full path through the public gateway
curl -v https://stg.example.io/playout
Then in browser devtools → Network tab on the live URL:
- [ ] Initial page load returns 200, Server: nginx (not an APISIX-branded 404).
- [ ] All JS/CSS asset requests are prefixed (/playout/static/...) and return 200.
- [ ] Client-side navigation (clicking in-app links) keeps the /playout prefix in the URL bar.
- [ ] Refreshing on a deep link (e.g. /playout/dashboard) still loads correctly (SPA fallback).
- [ ] Auth/login round-trip (redirect out to IdP, redirect back) lands back under /playout, not root.
- [ ] Session-expiry (401) handling redirects to /playout, not root.
Diagnostic tip: reading a "404" response correctly¶
A 404 with Server: APISIX/x.x.x in the header can come from two different places:
1. APISIX itself generated the 404 (no route matched) — body is typically a plain JSON error.
2. The app's nginx pod generated the 404, and APISIX just passed it through untouched (its own Server header persists on the response) — body will look like nginx's default HTML error page (<hr><center>nginx/x.x.x</center>).
Check the response body, not just the Server header, to know whether the fault is in gateway routing or inside the pod.
Repeatable checklist for adding a new app under this scheme¶
For each new app (e.g. /tellyboard), using the recommended Option A (fully self-namespaced) pattern:
-
vite.config.js— setbase: '/tellyboard/'. - Ensure the app's own API/asset/upload client code targets paths under
/tellyboard/...(e.g./tellyboard/api/...), not root-relative paths. - Dockerfile —
COPY --from=build /app/dist /usr/share/nginx/html/tellyboard. - nginx — add
location /tellyboard { ... try_files $uri $uri/ /tellyboard/index.html; }pluslocation /tellyboard/api/,/tellyboard/assets/, etc. sub-blocks proxying to that app's backends. - Router —
<Router basename={import.meta.env.BASE_URL}>. - Audit
window.location.hrefusages in this app's codebase for hardcoded root paths. - New private
HTTPRoute— single rule matchingPathPrefix: /tellyboard, pointing attellyboard-service. - No changes needed on the public
ApisixRoute— the catch-all already covers it. - No collision risk with other apps — each app fully owns its own path namespace.