Skip to content

Commit

Permalink
Fix for properly redirecting a path with no trailing slash to its dir…
Browse files Browse the repository at this point in the history
…ectory
  • Loading branch information
conortm committed Oct 12, 2018
1 parent 54e537a commit 53817c5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
25 changes: 22 additions & 3 deletions main.tf
Original file line number Diff line number Diff line change
@@ -1,9 +1,28 @@
locals {
public_dir_with_leading_slash = "${length(var.public_dir) > 0 ? "/${var.public_dir}" : ""}"
static_website_routing_rules = <<EOF
[{
"Condition": {
"KeyPrefixEquals": "${var.public_dir}/${var.public_dir}/"
},
"Redirect": {
"Protocol": "https",
"HostName": "${var.domain_name}",
"ReplaceKeyPrefixWith": "",
"HttpRedirectCode": "301"
}
}]
EOF
}

resource "aws_s3_bucket" "static_website" {
bucket = "${var.domain_name}"

website {
index_document = "index.html"
error_document = "error.html"

routing_rules = "${length(var.public_dir) > 0 ? local.static_website_routing_rules : ""}"
}

tags = "${merge(map("Name", "${var.domain_name}-static_website"), var.tags)}"
Expand All @@ -13,7 +32,7 @@ data "aws_iam_policy_document" "static_website_read_with_secret" {
statement {
sid = "1"
actions = ["s3:GetObject"]
resources = ["${aws_s3_bucket.static_website.arn}${var.public_dir}/*"]
resources = ["${aws_s3_bucket.static_website.arn}${local.public_dir_with_leading_slash}/*"]

principals {
type = "AWS"
Expand All @@ -34,13 +53,13 @@ resource "aws_s3_bucket_policy" "static_website_read_with_secret" {
}

locals {
s3_origin_id = "cloudfront-distribution-origin-${var.domain_name}.s3.amazonaws.com${var.public_dir}"
s3_origin_id = "cloudfront-distribution-origin-${var.domain_name}.s3.amazonaws.com${local.public_dir_with_leading_slash}"
}

resource "aws_cloudfront_distribution" "cdn" {
origin {
domain_name = "${aws_s3_bucket.static_website.website_endpoint}"
origin_path = "${var.public_dir}"
origin_path = "${local.public_dir_with_leading_slash}"
origin_id = "${local.s3_origin_id}"

custom_origin_config {
Expand Down
4 changes: 2 additions & 2 deletions variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ variable "domain_name" {
}

variable "public_dir" {
description = "Directory in S3 Bucket from which to serve public files"
default = "/public"
description = "Directory in S3 Bucket from which to serve public files (no leading or trailing slashes)"
default = "public"
}

variable "redirects" {
Expand Down

0 comments on commit 53817c5

Please sign in to comment.