Openai/691ddcec-579c-8003-b973-cdb692b1d5db

Revision as of 05:39, 20 November 2025 by Lukegao (talk | contribs) (by freem.ai...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


This conversation was exported from ChatGPT[1]

gpt-5-1 edit

User: How do i host a static website in node.js, but where the first folder is taken from the host name. edit

How do i host a static website in node.js, but where the first folder is taken from the host name.

So if people go to banana.com to my node.js app, it should serve the banana.com folder. And if nothing can be found a 404 need to be returned.

Assistant: Below is a simple and clean way to do this in Node.js + Express: edit

Below is a simple and clean way to do this in Node.js + Express:

✅ Goal edit

Map each hostname to a folder with the same name, e.g.:

banana.com   → ./sites/banana.com/
apple.com    → ./sites/apple.com/

If the file doesn’t exist → return 404.

✔️ Working Example (Express) edit

const express = require("express");
const path = require("path");
const fs = require("fs");

const app = express();

// all hosts served from ./sites/<hostname>/
const SITES_ROOT = path.join(__dirname, "sites");

app.use((req, res, next) => {
  const host = req.hostname; // e.g. "banana.com"
  const siteDir = path.join(SITES_ROOT, host);

  // Check if the site folder exists
  if (!fs.existsSync(siteDir)) {
    return res.status(404).send("Site not found");
  }

  // Create a static handler for this request
  express.static(siteDir)(req, res, (err) => {
    if (err) return next(err);
    res.status(404).send("File not found");
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(<code>Listening on ${PORT}</code>));

✔️ Folder structure edit

your-app/
  server.js
  sites/
    banana.com/
      index.html
    apple.com/
      index.html

✔️ How it works edit

  1. Every request hits a middleware.
  2. We inspect req.hostname to know which folder to serve.
  3. We check if ./sites/<hostname> exists.
  4. We attach a static-file handler dynamically to serve from that folder.
  5. If no file matches → 404.

✔️ Notes / Tips edit

If using reverse proxies (Nginx, Cloudflare, etc.) edit

Make sure they pass the correct Host header.

Wildcard domains (e.g., *.example.com)? edit

You can adapt it:

const host = req.hostname.split(':')[0];
const sub = host.split('.')[0];
const siteDir = path.join(SITES_ROOT, sub);

If you want, I can help you: ✔ create a version using only Node (no Express) ✔ support for default domain fallback ✔ caching static handlers for performance ✔ support for multi-level domain matching

Just tell me!

References edit

  1. "Host static site Node.js". ChatGPT. Retrieved 2025-11-20.