DEV Community

Robert Reiz
Robert Reiz

Posted on

Redirects with AWS S3

Assume you have a web application deployed on AWS ECS Fargate, with an ALB (Application Load Balancer) in front of it. The ALB is doing the SSL termination as well. Your domain mydomain.com is mapped to the ALB and everything works fine!

But now you want to redirect the traffic from www.mydomain.com to your main domain mydomain.com. Of course you could create another ALB for that, but that would increase your monthly AWS bill. A much better and cheaper solution is to use S3 for that.

First, let's create a new S3 bucket for that purpose. If you work with Terraform, you just need to customize this code snippet:

resource "aws_s3_bucket" "www_redirect" {
  bucket = var.s3_www
  acl    = "public-read"

  website {
    redirect_all_requests_to = "https://mydomain.com"
  }

  tags = {
    Name        = var.s3_www
    Environment = var.environment
  }
}
Enter fullscreen mode Exit fullscreen mode

If you don't use Terraform, simply read this article to find out how to do it manually.

That code snippet creates a new empty S3 bucket with public read permissions. The S3 bucket is empty. It doesn't contains any files/objects. It is configured that way that it redirects all requests immediately to https://mydomain.com.

Now we only need to map the subdomain www to that S3 bucket. In your DNS Zone file you have to create an A record with the value of the S3 bucket address. If your domain is managed by AWS Route 53, you navigate to the desired zone file and click "Create record". Then you should see something like this:

Route 53 routing

Simple routing is fine for us. In the next form you have to define the subdomain "www" and choose the Endpoint to which it should be mapped. Here we have to choose "Alias to S3 website endpoint".

Alt Text

Next, you have to choose your region and the corresponding S3 bucket, which we just created before.

Alt Text

And that's it! Now the subdomain "www" is mapped to the S3 bucket, which will redirect every request to "https://mydomain.com".

Top comments (0)