Jump to content

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

From freem


This conversation was exported from ChatGPT[1]

gpt-5-1[edit | edit source]

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

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 | edit source]

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

✅ Goal[edit | edit source]

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 | edit source]

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 | edit source]

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

✔️ How it works[edit | edit source]

  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 | edit source]

If using reverse proxies (Nginx, Cloudflare, etc.)[edit | edit source]

Make sure they pass the correct Host header.

Wildcard domains (e.g., *.example.com)?[edit | edit source]

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 | edit source]

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