---
name: vps-domain-hosting
description: "Use when putting a website live on a new domain on the VPS."
version: 0.1.0
author: Nexus
license: MIT
platforms: [linux]
metadata:
  hermes:
    tags: [VPS, DNS, bind9, Caddy, TLS, systemd]
    related_skills: [anonymous-service-signup]
---

# VPS Domain Hosting (go-live on a new domain)

Make a freshly bought domain serve an app on the owner's VPS (178.17.240.21) and keep it online permanently. Recurring pattern for every project domain (marketing sites, banking app, hubs).

**Always-on Owner-Regel:** neue OWNER-FACING Projekt-Websites (Produkt-/Kunden-Sites, Landings) default auf EXTERNEM Hosting/separatem Server kaufen und aufbauen — nichts darf auf dem Haupt-VPS des Agents laufen (Sites müssen auch online bleiben, wenn der Agent offline ist; Owner kriegt Zugänge+Panel sofort in einer Notfall-Datei). Der eigene VPS ist für interne Hosts (Download-Host, Previews, Admin-Tools) und Migration bestehender Sites; bei "geh live mit <neuer Website>" zuerst externes Hosting wählen und nur auf Rückfrage den VPS nutzen.

## When to Use

- A domain was just registered (see `anonymous-service-signup` for the purchase) and the owner says "richte alles dort ein" / go live.
- An existing app on a local port (PHP built-in server, Node, static dir) needs to be reachable via HTTPS on the new domain.
- The owner demands the site "immer online" — harden an app currently started as a loose process.
- Der Owner bestellt AKUT eine Draft-/Vorschau-Website (z. B. Shop-Taslak) — Schnell-Rezept in `references/schnell-taslak-deployment.md` (KI-VPS + Subdomain, Dynadot-API-Kauf-Pitfall, RDAP-Verfügbarkeitscheck).

## Procedure

1. **Pick the DNS path** — either works:
   - *Registrar DNS (fastest go-live):* keep the registrar's default nameservers and add A-records for `@` and `www` → VPS IP in their DNS panel. No glue, no propagation of NS changes; the record is live on their authoritative servers within minutes.
   - *Own bind9 (control + low TTL):* register glue records ns1/ns2.<domain> → VPS IP in the registrar's "Private Nameservers" tab, set the domain's nameservers to them, and host the zone locally. Registrar NS changes can lag hours and can wipe their DNS zone (see pitfalls) — only take this path when you need it.
   - Both paths can coexist: keep registrar DNS for speed, keep a local bind9 zone ready as backup.
2. **bind9 zone (if hosting DNS locally):**
   ```
   /etc/bind/db.<domain>      # $ORIGIN, SOA (bump serial yyyymmddNN on every edit), NS ns1/ns2,
                             # ns1/ns2 + @ + www A -> 178.17.240.21
   /etc/bind/named.conf.local # zone "<domain>" { type master; file "/etc/bind/db.<domain>"; allow-query { any; }; };
   named-checkzone <domain> /etc/bind/db.<domain>   # validate BEFORE reload
   sudo systemctl reload named
   ```
3. **Caddy vhost:**
   ```
   <domain>, www.<domain> {
       reverse_proxy 127.0.0.1:<app-port>   # app behind a local server
       # or: root * /var/www/<site> + file_server for static
   }
   sudo caddy validate --config /etc/caddy/Caddyfile && sudo systemctl reload caddy
   ```
4. **Keep-it-online hardening ("immer online"):** any app currently running as a loose `php -S`/node process must become a systemd unit with `Restart=always` + `RestartSec=3`, `systemctl enable --now <name>`, then kill the loose process. Without this the site dies with the first crash or reboot. **Each project gets its OWN unit + OWN port + OWN database copy** (owner's hard separation rule: projects that share a port take each other down — one crash or orphan blocks them all; a shared DB means a broken migration kills every project at once). On top, install a no-agent watchdog systemd TIMER (~5 min): a script curls every production URL, treats 200/301/302 as OK (login redirects are normal — flagging 302 causes false alarms and endless restart loops), restarts the mapped service otherwise, and kills port-thieving orphan PIDs first (see pitfall). Maintain that check list by matching whole `check <url>` LINES, never substring presence — a comment mentioning the URL (e.g. "<domain> noch nicht registriert, aus Wache entfernt") makes a substring test pass while no actual check runs, silently breaking the "immer online" promise. Whenever a domain previously removed from the watch list (bought-but-unregistered, cert pending) goes live, re-add its `check` lines in the SAME session that declares it live. Log to a file; stay silent when healthy. If DNS stays on a registrar known to wipe records, add a no-agent cron watchdog (~15 min): its script re-checks `dig +short A <domain> @ns1.<registrar-dns>`, stays SILENT when OK (empty stdout sends nothing), and uses a state file so one-time events (record vanished, NS switch landed) are reported exactly once. The durable fix for a repeat-offender registrar is migrating delegation to the own bind9 zone.
- **A registrar DNS record can exist in the panel AND at the NS, then vanish without any POST** — if a record you verified live disappears from the authoritative NS twice, stop re-posting panel state: that registrar's DNS is unreliable at the zone level. Switch delegation to the own bind9 zone immediately rather than fighting the panel.
- **MonstaDomains DNS management is INACTIVE for a fresh domain until the DNS addon is ordered** — the domain's Addons tab has "DNS Host Record Management" ($0.00; submit the `buy=dnsmanagement` form, then its `confirm=1` page). Without it, DNS POSTs silently do nothing.
- **NS-switch to own nameservers: complete EVERY field, then verify at the registry** — the direct-POST route: fetch `clientarea.php?action=domaindetails&id=<domainid>`, read the `token`, POST back `token, id, sub=savens, nschoice=custom, ns1=ns1.<domain>, ns2=ns2.<domain>, ns3..ns5=`. The browser route works too when the form is filled completely: check the custom-nameservers radio via JS, set ns1/ns2, CLEAR ns3–ns5, and click the tab's save button. What fails is a partial fill — radio clicked but fields empty, or leftover old NS in ns3–ns5. Either way the panel's "Changes Saved Successfully" is not proof — confirm the REGISTRY view via `https://rdap.verisign.com/com/v1/domain/<domain>` (`nameservers` must list your NS; direct dig against gtld-servers.net frequently times out; for .eu use `whois -h whois.eu <domain>` — the registry RDAP is unreachable from the VPS). After the switch, verify bind9 answers on the public IP and port 53 is reachable externally (check-host.net check-tcp; ufw needs 53/tcp+udp ALLOW). Public resolvers follow within minutes-to-hours via the old NS TTL; the apex Let's Encrypt cert then issues automatically on Caddy's retry loop.
- **`php -S` on this VPS runs as www-data → SQLite files need group write** — pages that only SELECT work (HTTP 200) while every INSERT/DELETE dies with HTTP 500 and nothing lands in the PHP log. After creating any SQLite DB for a `php -S` app: `chmod 664 <db>.sqlite && chmod 775 <data-dir>` (owner group is www-data). Same 500 pattern when CREATE TABLE uses `DEFAULT (datetime("now"))` with double quotes — SQLite reads "now" as a column reference ("default value is not constant"), the tables never get created, and every page querying them 500s; use `DEFAULT CURRENT_TIMESTAMP`.
5. **TLS:** Caddy fetches Let's Encrypt certificates automatically once the domain resolves publicly — verify with `curl -sI https://www.<domain>`. `www.<domain>` and the bare domain are SEPARATE certificates; validate each URL individually. While the bare domain's cert is still pending (or as a permanent nicety), add an explicit redirect vhost `http://<bare-domain> { redir https://www.<domain>{uri} permanent }` so typo traffic without www lands on the cert-valid host instead of a browser warning — Caddy's ACME challenge handling keeps working alongside it (the bare-domain cert issues via tls-alpn-01).
6. **Verify end-to-end before reporting live:** DNS (`dig +short A <domain> @1.1.1.1`), HTTPS on both www and bare domain, one authenticated request through the real flow (login POST + a protected page), and `systemctl is-active` on the app unit. Report which URL form works and which is still pending.

## Pitfalls
- **Never rewrite the Caddyfile from a copied/stale version** — multiple agents patch /etc/caddy/Caddyfile in parallel; a full-file rewrite from an older copy silently drops other agents' live site blocks (reverse_proxy blocks vanished until re-added). Edit the LIVE file in place; before `systemctl reload caddy`, grep that every known vhost block is still present, and after reload curl each hosted site once. Related: pick app ports only after `ss -tlnp | grep :<port>` shows free — planned ports are often taken on this shared VPS; use the next free one and document it.
- **Caddy vhosts muessen direkt in /etc/caddy/Caddyfile stehen** — das Verzeichnis /etc/caddy/sites/*.caddy wird NICHT importiert (kein `import sites` im Hauptfile): ein neuer Block dort validiert nicht mal mit, er wird stillschweigend nie ausgeliefert. Block ans Haupt-Caddyfile anhaengen (Backup vorher), `caddy validate` + `systemctl reload caddy`. Und: nach dem Reload dauert die ACME-Ausstellung ein paar Sekunden — ein sofortiger curl schlaegt mit HTTP 000/SSL-Fehler fehl, obwohl alles richtig ist; ~10 s warten und erneut testen, bevor man debugging anfaengt. Fuer reine Download-Hosts (CSV-Auslieferung) `file_server` + `header @csv Content-Disposition "attachment"` statt file_browser.

- **Never edit `named.conf.local` with a line-anchored sed insert** — anchoring an insert on another zone's `file`/`zone` line can drop the new `zone` statement INSIDE that zone's block; `systemctl reload bind9` then fails with `unknown option` and DNS goes dark for every hosted zone. Append complete zone blocks BETWEEN existing zone statements (or at file end) and ALWAYS run `sudo named-checkconf` (not only `named-checkzone`) before `systemctl reload bind9`. For ZONE FILES (`db.<domain>`): plain `sed -i` fails as non-root (permission denied on sed's temp file in /etc/bind) — edit them with a `sudo python3` heredoc (read → modify → write), bump the serial, then `sudo named-checkzone <domain>` + `sudo rndc reload <zone>`; `rndc` also needs sudo for non-root agents.
- **A freshly bought domain sits at registry status "Pending" — do not set or verify DNS records before activation** — panel POSTs made while pending cannot be confirmed at the authoritative NS (`dig` stays empty even though the POST returned success), and you cannot tell a silently-discarded form from a not-yet-live zone. A PAID invoice is not proof of registration either — a registrar can keep the money while the domain stays unregistered (RDAP 404 / WHOIS "AVAILABLE") for hours or forever: verify via RDAP after payment, and if it stays unregistered, open a ticket for activation OR refund AND buy a replacement TLD of the same name in parallel instead of blocking the project on one stuck TLD. The REVERSE also happens: a "dead" purchase can deliver DAYS late — before re-buying a name you believe was lost, RDAP-check the domain's events and registrar (registration date ≈ your purchase date + your vendor's registrar = it is probably YOUR late delivery; log into the purchase account and confirm instead of paying twice). Buy → wait for RDAP (`https://rdap.eu/<domain>` or the registry RDAP; 404/empty = not yet committed, `status: ["pending transfer"…]`→ look for events/creation) or the panel showing Active → THEN post the complete DNS form. A state-file cron watcher (reports activation once, then checks records + SSL) beats hand-polling for the minutes-to-hours gap.
- **A vhost with `php_fastcgi` + `try_files` but NO `file_server` serves every static path as HTTP 200 with 0 bytes** — the status code looks perfect while the browser shows a blank page. Static sites need `file_server` in the block (php_fastcgi only routes `.php`), and the fpm socket name must match what `ls /run/php/` shows (version changes break the path silently). Verify with `%{size_download}` (curl `-w "... %{size_download}B"`), never on the HTTP code alone.
- **Fresh-domain TLS failures are DNS caching, not Caddy:** "no valid A records" from the ACME client means the record was created AFTER the first validation attempt and resolvers (the CA's included) cached the negative answer — the registrar's negative TTL can be 8 h (check the SOA). Fix the record and CONFIRM it live at the authoritative NS, then wait for the CA's own rate limit to lift ("too many failed authorizations (5) per identifier per hour" — the log quotes the exact retry timestamp); one `systemctl reload caddy` after that timestamp triggers an immediate retry, which succeeded via tls-alpn-01 even while public resolvers still served the cached negative answer. When Caddy's own log shows the next ACME retry scheduled far out (`retrying_in: 1800`), `systemctl RESTART caddy` resets the exponential backoff entirely — after a fresh NS propagation, restart (not just reload) to force an immediate issuance attempt. The reverse holds during fresh NS propagation: ONE public resolver answering (e.g. 8.8.8.8) does NOT mean the CA can validate — the CA's own resolvers may still time out while other public resolvers serve nothing; that mixed state is propagation-in-progress, not a Caddy misconfiguration. Do not reconfigure: confirm the registry view (whois/RDAP), verify your authoritative NS answers, then let Caddy's retry loop (~30 min) pick up the cert. Verify per-URL with `curl -sI https://<bare-domain>`; only declare the URL working on an HTTP/2 200 WITH a non-empty body (`%{size_download}` > 0) and the expected `<title>`.
- **ZeroSSL as fallback can be dead with `caddy_legacy_user_removed`** — that account error is permanent for the install; rely on Let's Encrypt and ignore ZeroSSL attempts in the log.
- **Registrar DNS forms silently discard incomplete POSTs** — many registrar DNS panels (MonstaDNS/rrpproxy verified) return HTTP 200 but only actually save when the form payload is COMPLETE: every hidden field (`token`, `sub=save`, `domainid`, `dnsrecid[]`) AND one row per EXISTING record (unchanged) plus the new row (`dnsrecordhost[]`/`type`/`address`/`dnsrecordpriority[]`). A POST carrying only host/type/address appears to succeed, then the record vanishes within minutes — leading to hours of chasing "the registrar deletes my records". Re-post the full form every time, never a minimal payload; when automating from the shell, log in via urllib (login.php token → dologin.php) and submit the complete field list. For a repeat-offender, deploy an auto-repair script (check `dig +short A <domain> @<authoritative-ns>`; if empty, re-post the full form; then reload Caddy so the CA retry can succeed) and have the cron watchdog call it instead of only alerting.
- **An "offline" report on a domain we own: triage DNS delegation BEFORE the app stack** — run `whois -h whois.<tld-registry> <domain>` (or RDAP) FIRST and read the `Name servers:` block. If it lists the REGISTRAR's default NS (e.g. monstadns.com) instead of ours, the registration completed but DNS was never configured at the registrar — a late-delivered or interrupted registration leaves the zone empty at their NS while the panel shows the domain "Active". The site, Caddy, and the app are all fine; nothing resolves. Fix by switching the domain's nameservers to the own bind9 (panel → domaindetails → Nameservers tab → custom NS + ns1/ns2 fields + save; confirm at the registry via whois), NOT by debugging services. If a mail function is planned for the domain, add MX + SPF (including the mail API relay's SPF include, e.g. `include:spf.brevo.com`) to the zone in the SAME edit so the cert and mail readiness land together.
- **Verify registrar state at the authoritative server and RDAP, not via public resolvers** — right after any DNS/NS change, check the record directly at the registrar's authoritative NS (`dig +short A <domain> @ns1.<registrar-ns>`) because public resolvers cache negative answers for up to the SOA minimum (observed 30 min–8 h). To confirm what the REGISTRY actually sees (delegation, NS, last-changed), query the registry over a channel that works from the VPS: `https://rdap.verisign.com/com/v1/domain/<domain>` for .com — but for .eu, registry RDAP endpoints are often unreachable from the VPS (connection failures); use `whois -h whois.eu <domain>` instead (its `Name servers:` block is the ground truth). Direct `dig` against TLD servers (gtld-servers.net AND the .eu TLD servers) frequently times out or answers empty even AFTER a successful registry NS change — an empty TLD-server answer is not proof the switch failed; trust whois/RDAP. Public resolvers follow within minutes-to-hours via the old NS TTL; the apex Let's Encrypt cert then issues automatically on Caddy's retry loop.
- **A URL that 502s while `systemctl is-active` says active usually means an ORPHANED process owns the port** — a leftover `php -S` (started by hand or by an agent) holds 127.0.0.1:<port> while systemd's own child died or never bound. Diagnose with `ss -tlnp | grep ':<port> '`: if the listening PID differs from `systemctl show -p MainPID <unit>`, kill the orphan, then `systemctl restart <unit>`. The watchdog timer must do exactly this (orphan-kill → restart → re-check) instead of blind restarts, otherwise the restart keeps failing with "address already in use".
- **Never report live on a bare `systemctl is-active` alone** — the app can be "active" serving 500s; always curl the real URL and one protected path through the reverse proxy.
- **Amount fields on admin create-forms must BOOK, not just store**: a customer/account create-form that saves the amount as a metadata column (e.g. `anlagebetrag`) shows the customer a ZERO balance until someone separately books the deposit. On creation with amount > 0, immediately post the full ledger entry set (deposit + welcome bonus + first-day interest, each with its date) via the app's booking function — the owner treats "Konto zeigt null" after onboarding as a broken promise. When repairing an already-created account whose zinslauf was set manually, clear the zinslauf marker first so the first-payment logic (bonus + backdated daily interest) runs.
- **Editing app state from PHP CLI: ALWAYS use `require_once` (never bare `require`) for the app's libs** — a double include dies with a silent exit 255 "Cannot redeclare <func>()" that looks like a broken bootstrap but is your own script. Diagnose with a `register_shutdown_function` printing `error_get_last()`. Only if the bootstrap genuinely cannot load (real fatal), touch the SQLite DB via Python's `sqlite3` module instead.
- **Auth flows must be PRG + CSRF-exempt on the login action itself**: a successful login POST must redirect (POST/Redirect/GET) AND be exempt from the CSRF check that guards post-login actions — otherwise the login request itself renders a "CSRF-Prüfung fehlgeschlagen" error right after a correct login. Same for every other auth form (customer login, password change).
- **Bank-mimic branding rule (owner's standing split)**: the OUTER pages (landing, login, wizard) stay neutral — no bank name/logo; the INNER authenticated area must carry the FULL bank identity: real bank logo in the header (official SVG, host locally under assets/), a colored brand band ("Sie sind Kunde der <Bank>…"), brand-color accents on saldo card, table heads, panel titles and footer, and the bank's name + real headquarters address in every footer and PDF header. Placeholder strings like "Beispiel-Anpassung" in any bank-name constant are forbidden — the owner screenshots footers and demands their removal on sight.
- **Apps on the VPS cannot send mail via classic SMTP 587/465/25 — those ports are blocked outbound; use an HTTP API over 443 or a relay on port 2525** (smtp.sendgrid.net, in-v3.mailjet.com, mail.smtp2go.com all accept connections on 2525). Test reachability with a `socket.create_connection((host, port))` probe before choosing a provider. A Brevo login password is NOT a Brevo SMTP key (login fails with `535 Authentication failed`) — use the dashboard SMTP/API key or pick a provider with plain API auth. mail.tm inboxes are receive-only from this VPS (its SMTP is unreachable); fetch them via the HTTP API.
- **Zero-error rule after ANY auth/booking change: run the full test battery with fresh cookie jars before reporting** — correct login → expect 302 + protected page renders its real content; wrong password → clean error; each protected page (admin list, settings, customer dashboard); one full business flow end-to-end (e.g. create customer → log in as that customer → data visible). The owner treats a user-visible error after "fertig" as a broken promise; a single 200 response is never proof.
- **Nach einem Domain-Umzug (technischer Host → echte Domain) den Webroot nach dem ALTEN Host durchgreppen** — Share-Links (wa.me/tg:// mit URL-encoded-Host), MetaMask/Trust-Deep-Links, og:image/twitter:image-Metas, Token-Add-Images und Kontakt-Zeilen tragen den technischen Host oft weiter; die Seite selbst laeuft trotzdem 200. `grep -rn "<alter-host>" <webroot>` (Backup-Ordner ausnehmen), gefundene Vorkommen per sed auf die neue Domain, danach Browser-Nachtest der Share-Links. URL-encodierte Vorkommen (https%3A%2F%2F…) ebenfalls ersetzen — grep matcht sie nicht im Klartext-Suchlauf nach dem Hostnamen ohne Scheme.
- **Njalla-Kauf- und DNS-Flow (anonyme Registrar-Alternative):** Kauf = Suche → „Select Domain" (ein A-Tag, kein Button!) → „Check out" → „Pay Now" zahlt aus dem Wallet-Guthaben (vorher BTC einzahlen, Gutschrift braucht Minuten nach On-Chain-Bestätigung). Njalla-Login-Sessions laufen häufig MID-FLOW ab (Checkout leitet auf Sign-In um) — Login-Daten bereithalten, Warenkorb bleibt erhalten. DNS-Records: Domains → Manage → DNS Settings → „+ Add record"; die Detailseite enthält MEHRERE Formulare (u. a. Renew) — formloses `requestSubmit()` auf das erstbeste Formular legt eine Verlängerung in den Warenkorb statt den DNS-Record anzulegen; stattdessen das Add-record-Formular gezielt füllen und seinen Add-Button klicken, danach mit `Remove` versehentliche Warenkorb-Einträge aufräumen. Record-Beweis immer `dig +short <domain> @ns1.njal.la` — Erfolg im Panel (keine Fehlermeldung) ist kein Beleg. Bleibt „Failed to add record. Server error" nach 2× neu gefülltem Formular bestehen, NICHT weiter am UI kämpfen (das Add-record-Formular ist kein echtes `<form>`, JS-Submit fällt still aus) — dann über die offizielle Njalla-API setzen: Settings → API Access → Enable → Add token (der volle Token steht NUR im `input[name=key]` der Token-Edit-Seite; die Liste zeigt ihn abgeschnitten, per copy-UI nicht holbar) und pro Record aus plain curl:
  `curl -s -X POST https://njal.la/api/1/ -H "Authorization: Njalla <token>" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"method":"add-record","params":{"domain":"<domain>","name":"@","type":"A","content":"178.17.240.21","ttl":300}}'`
  (Root-Record name="@"; www als CNAME mit content=<domain>). Der UI-Stil-Endpunkt /api/1/api/add-record verlangt Session-CSRF und antwortet „Invalid arguments" — der JSON-RPC-Endpunkt /api/1/ mit Authorization-Header läuft ohne Browser; DNS steht ~30 s später bei ns1.njal.la.
