about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAlan Pearce2023-11-05 13:32:14 +0100
committerAlan Pearce2023-11-05 17:18:29 +0100
commit6c0b9fb5773f48d86008f737704b735c0787e788 (patch)
tree6c3fe0ab0274fd21b058d17e3160027c3466e1c2
parent3a9b920d4981ac28becb9634ec964dc2e2104401 (diff)
downloadwebsite-6c0b9fb5773f48d86008f737704b735c0787e788.tar.lz
website-6c0b9fb5773f48d86008f737704b735c0787e788.tar.zst
website-6c0b9fb5773f48d86008f737704b735c0787e788.zip
Automatically redirect other hostnames to the configured base_url
-rw-r--r--config.toml1
-rw-r--r--fly.toml2
-rw-r--r--src/app.ts18
3 files changed, 20 insertions, 1 deletions
diff --git a/config.toml b/config.toml
index e3a23be..9fd866d 100644
--- a/config.toml
+++ b/config.toml
@@ -1,5 +1,6 @@
 default_language = "en-GB"
 base_url = "https://alanpearce.eu"
+redirect_other_hostnames = true
 
 title = "Alan Pearce"
 description = "Developer, Emacs User"
diff --git a/fly.toml b/fly.toml
index aa31e61..7e09b9b 100644
--- a/fly.toml
+++ b/fly.toml
@@ -27,3 +27,5 @@ primary_region = "ams"
   method = "GET"
   timeout = "5s"
   path = "/health.txt"
+  [http_service.checks.headers]
+    Host = "alanpearce.eu"
diff --git a/src/app.ts b/src/app.ts
index e33bc72..8ba2d8a 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -14,6 +14,9 @@ Sentry.init({
   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 @@ export const metricsServer = {
 
 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 @@ export const 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())) {