Skip to content

Commit

Permalink
www redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
andreiio committed Nov 21, 2024
1 parent b1eeb1a commit e0f8e79
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
18 changes: 18 additions & 0 deletions terraform/cloudfront.tf
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ resource "aws_cloudfront_distribution" "main" {
origin_request_policy_id = aws_cloudfront_origin_request_policy.default.id
viewer_protocol_policy = "redirect-to-https"
compress = true

function_association {
event_type = "viewer-request"
function_arn = aws_cloudfront_function.www_redirect.arn
}
}

default_cache_behavior {
Expand All @@ -42,6 +47,11 @@ resource "aws_cloudfront_distribution" "main" {

cache_policy_id = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad" #Managed-CachingDisabled
origin_request_policy_id = aws_cloudfront_origin_request_policy.admin.id

function_association {
event_type = "viewer-request"
function_arn = aws_cloudfront_function.www_redirect.arn
}
}

restrictions {
Expand Down Expand Up @@ -124,3 +134,11 @@ resource "aws_cloudfront_origin_request_policy" "admin" {
query_string_behavior = "all"
}
}

resource "aws_cloudfront_function" "www_redirect" {
name = "${local.namespace}-www-redirect"
runtime = "cloudfront-js-1.0"
comment = "Redirects ${var.domain_name} to www.${var.domain_name}"
publish = true
code = file("${path.module}/functions/www-redirect.js")
}
22 changes: 22 additions & 0 deletions terraform/functions/www-redirect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
function handler(event) {
if (!event.request.headers.hasOwnProperty('host')) {
return {
statusCode: 404,
statusDescription: 'Not Found',
}
}

if (!event.request.headers.host.value.startsWith('www.')) {
return {
statusCode: 301,
statusDescription: 'Moved Permanently',
headers: {
location: {
value: `https://www.${event.request.headers.host.value}${event.request.uri}`,
},
},
}
}

return event.request
}

0 comments on commit e0f8e79

Please sign in to comment.