all repos — homestead @ a9895359056220647d864a0cb3a121d95e173a22

Code for my website

Automatically redirect other hostnames to the configured base_url

Alan Pearce
commit

a9895359056220647d864a0cb3a121d95e173a22

parent

41ea72035b69b7c9f36a3c69de5b2cf513592069

2 files changed, 19 insertions(+), 1 deletion(-)

jump to
M fly.tomlfly.toml
@@ -27,3 +27,5 @@ interval = "30s"
method = "GET" timeout = "5s" path = "/health.txt" + [http_service.checks.headers] + Host = "alanpearce.eu"
M src/app.tssrc/app.ts
@@ -14,6 +14,9 @@ release: `homestead@${Bun.env.FLY_MACHINE_VERSION}`,
tracesSampleRate: 1.0, }); +const expectedHostURL = new URL( + Bun.env.NODE_ENV === "production" ? config.base_url : "http://localhost:3000", +); const defaultHeaders = { ...config.extra.headers, vary: "Accept-Encoding",
@@ -128,7 +131,8 @@ } satisfies Serve;
export const server = { fetch: async function (request) { - const pathname = new URL(request.url).pathname.replace(/\/\/+/g, "/"); + const url = new URL(request.url); + const pathname = url.pathname.replace(/\/\/+/g, "/"); const endTimer = metrics.requestDuration.startTimer({ path: pathname }); const transaction = Sentry.startTransaction({ name: pathname,
@@ -136,10 +140,22 @@ op: "http.server",
description: `${request.method} ${pathname}`, tags: { url: request.url, + "http.host": request.headers.get("host"), "http.method": request.method, "http.user_agent": request.headers.get("user-agent"), }, }); + if ( + config.redirect_other_hostnames && + request.headers.get("host") !== expectedHostURL.host + ) { + return new Response("", { + status: 301, + headers: { + location: new URL(pathname, expectedHostURL).toString(), + }, + }); + } try { const file = files.get(pathname); if (file && (await file.handle.exists())) {