From 3ff4843c8ac7019be100aafc0c5bcca225942bf1 Mon Sep 17 00:00:00 2001 From: Rob Mosher Date: Fri, 27 Sep 2024 04:20:42 -0400 Subject: [PATCH] Add redirect from www to bare domain --- .eslintrc.json | 1 + .../handler-on-viewer-request.js | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 cloudfront-functions/handler-on-viewer-request.js diff --git a/.eslintrc.json b/.eslintrc.json index 5a2265f..dc2861a 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -17,6 +17,7 @@ "plugin:tailwindcss/recommended" ], "ignorePatterns": [ + "cloudfront-functions/*", ".eslintrc.cjs", "dist", "tailwind.config.ts" diff --git a/cloudfront-functions/handler-on-viewer-request.js b/cloudfront-functions/handler-on-viewer-request.js new file mode 100644 index 0000000..5b84b7b --- /dev/null +++ b/cloudfront-functions/handler-on-viewer-request.js @@ -0,0 +1,25 @@ +// AWS runtime: 'cloudfront-js-2.0' +// This function is intended to run as part of the 'Viewer Request' event in CloudFront, where it +// checks and redirects requests from 'www.whoisthecutest.com' to 'whoisthecutest.com'. + +function handler(event) { + var request = event.request; + var headers = request.headers; + + var bareDomain = 'whoisthecutest.com'; + + if (headers.host && headers.host.value === 'www.' + bareDomain) { + return { + statusCode: 308, + statusDescription: 'Permanent Redirect', + headers: { + // Redirects to the bare domain without preserving the path (request.uri). + // Since the site is a single-page application, only the base domain is needed for the redirect. + location: { value: 'https://' + bareDomain }, + }, + }; + } + + // If the host doesn't match 'www.whoisthecutest.com', proceed without redirection. + return request; +}