Skip to content

Instantly share code, notes, and snippets.

@hussfelt
Last active April 2, 2024 21:25
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hussfelt/82d1180d5b1b3834de72e0829e3e585c to your computer and use it in GitHub Desktop.
Save hussfelt/82d1180d5b1b3834de72e0829e3e585c to your computer and use it in GitHub Desktop.
AWS and Terraform: Simplest redirect possible for redirecting traffic from one domain to another

AWS and Terraform site redirect

Using example.com as the input domain, this module will:

  • Create a Route53 zone for example.com
  • Create a bucket named example.com
  • Create a bucket named www.example.com
  • Create a Route53 A record example.com for the static website bucket of example.com
  • Create a Route53 A record www.example.com for the static website bucket of www.example.com

This is possibly the simplest way of sending traffic from one domain to another using AWS services. The only caveat is that two bucket names needs to be available on AWS S3.

  1. Put main.tf in a module folder, for example modules/site-redirect/main.tf

Use module like this within your terraform plan:

module "redirect_example_com" {
  source = "modules/site-redirect"

  domain   = "example.com"
  redirect = "https://send.traffic.here.example.com"

  # Accepts a provider, if you have multiple defined
  providers {
    "aws" = "aws"
  }
}

Credits and inspiration:

variable "domain" {
description = "Domain name of the redirect host"
}
variable "redirect" {
description = "URL that should be redirected to"
}
provider "aws" {}
resource "aws_s3_bucket" "redirect" {
bucket = "${var.domain}"
acl = "private"
website {
redirect_all_requests_to = "${var.redirect}"
}
}
resource "aws_s3_bucket" "www_redirect" {
bucket = "www.${var.domain}"
acl = "private"
website {
redirect_all_requests_to = "${var.redirect}"
}
}
resource "aws_route53_zone" "domain" {
name = "${var.domain}"
}
resource "aws_route53_record" "domain" {
name = "${var.domain}"
zone_id = "${aws_route53_zone.domain.zone_id}"
type = "A"
alias {
name = "${aws_s3_bucket.redirect.website_domain}"
zone_id = "${aws_s3_bucket.redirect.hosted_zone_id}"
evaluate_target_health = true
}
}
resource "aws_route53_record" "www_domain" {
name = "www.${var.domain}"
zone_id = "${aws_route53_zone.domain.zone_id}"
type = "A"
alias {
name = "${aws_s3_bucket.www_redirect.website_domain}"
zone_id = "${aws_s3_bucket.www_redirect.hosted_zone_id}"
evaluate_target_health = true
}
}
@hussfelt
Copy link
Author

@chorsnell - correct! :) Feel free to add a reference here if you modify the gist to allow this! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment