Skip to content

Commit

Permalink
fix: error page & enable multi-site redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
Alvin Januar committed Feb 12, 2024
1 parent fe5ac41 commit a648d53
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
26 changes: 26 additions & 0 deletions infra/cloudfront.tf
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ resource "aws_cloudfront_origin_access_control" "oac" {
signing_protocol = "sigv4"
}

resource "aws_cloudfront_function" "redirector" {
name = "astro-multi-page-cf-redirector-function"
runtime = "cloudfront-js-1.0"
comment = "Remap paths to index.html when request origin for multi-page sites"
publish = true
code = file("./redirector.js")
}

resource "aws_cloudfront_distribution" "s3_distribution" {
origin {
domain_name = aws_s3_bucket.bucket.bucket_regional_domain_name
Expand Down Expand Up @@ -41,13 +49,31 @@ resource "aws_cloudfront_distribution" "s3_distribution" {
forward = "none"
}
}
function_association {
event_type = "viewer-request"
function_arn = aws_cloudfront_function.redirector.arn
}

viewer_protocol_policy = "allow-all"
min_ttl = 0
default_ttl = 3600
max_ttl = 86400
}

custom_error_response {
error_caching_min_ttl = 10
error_code = 403
response_code = 200
response_page_path = "/index.html"
}

custom_error_response {
error_caching_min_ttl = 10
error_code = 404
response_code = 200
response_page_path = "/404.html"
}

# Cache behavior with precedence 0
ordered_cache_behavior {
path_pattern = "*"
Expand Down
15 changes: 15 additions & 0 deletions infra/redirector.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function handler(event) {
var request = event.request;
var uri = request.uri;

// Check whether the URI is missing a file name.
if (uri.endsWith("/")) {
request.uri += "index.html";
}
// Check whether the URI is missing a file extension.
else if (!uri.includes(".")) {
request.uri += "/index.html";
}

return request;
}

0 comments on commit a648d53

Please sign in to comment.