From 6bc1c8d16d37c811a520db4180a8cf35c7ddcb1b Mon Sep 17 00:00:00 2001 From: DaX Date: Fri, 31 Oct 2025 02:54:46 +0100 Subject: [PATCH] Add CloudFront Function for directory index routing - Create CloudFront Function to rewrite directory requests to index.html - Fix admin login page routing issue (/upadaj -> /upadaj/index.html) - Attach function to CloudFront distribution default cache behavior - Enables proper routing for all admin pages without .html extension --- terraform/cloudfront-frontend.tf | 14 ++++++++++++++ terraform/cloudfront-function.js | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 terraform/cloudfront-function.js diff --git a/terraform/cloudfront-frontend.tf b/terraform/cloudfront-frontend.tf index 9eabc71..a72509f 100644 --- a/terraform/cloudfront-frontend.tf +++ b/terraform/cloudfront-frontend.tf @@ -40,6 +40,15 @@ resource "aws_cloudfront_origin_access_control" "frontend" { signing_protocol = "sigv4" } +# CloudFront Function for directory index rewrites +resource "aws_cloudfront_function" "index_rewrite" { + name = "${var.app_name}-index-rewrite" + runtime = "cloudfront-js-1.0" + comment = "Rewrite directory requests to index.html" + publish = true + code = file("${path.module}/cloudfront-function.js") +} + # CloudFront distribution resource "aws_cloudfront_distribution" "frontend" { enabled = true @@ -74,6 +83,11 @@ resource "aws_cloudfront_distribution" "frontend" { default_ttl = 3600 # 1 hour max_ttl = 86400 # 24 hours compress = true + + function_association { + event_type = "viewer-request" + function_arn = aws_cloudfront_function.index_rewrite.arn + } } # Custom error responses for SPA routing diff --git a/terraform/cloudfront-function.js b/terraform/cloudfront-function.js new file mode 100644 index 0000000..535fa11 --- /dev/null +++ b/terraform/cloudfront-function.js @@ -0,0 +1,17 @@ +function handler(event) { + var request = event.request; + var uri = request.uri; + + // Check whether the URI is missing a file extension + if (!uri.includes('.')) { + // Check if URI ends with / + if (uri.endsWith('/')) { + request.uri += 'index.html'; + } else { + // Add /index.html to directory paths + request.uri += '/index.html'; + } + } + + return request; +}