S3 bucket redirect object does not redirect, bus instead downloads a file

44 Views Asked by At

I am using the @aws-sdk/client-s3 package to use AWS APIs. I try to upload redirect objects to my bucket using this code:

import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
const s3Client = new S3Client({ region: process.env.AWS_REGION });
    const putS3Command = new PutObjectCommand({
        Bucket: process.env.S3_BUCKET,
        Key: hashedUrl,
        WebsiteRedirectLocation: validatedRequestBody.url,
    });
await s3Client.send(putS3Command);

The command indeed succeeds, and I see the object in the bucket when I browse AWS S3 service: enter image description here

However, when I try to access the object (using presigned URL), I don't get redirected, but I just get download file of size 0.

I have the same behavior when I try to access the object using CloudFront. I set up a CloudFront distribution in front of this bucket. I expect to access the object via CloudFront and get a redirect.

Is there anything wrong with my PutObjectCommand?

I configured this S3 bucket using Terraform:

module "urls_s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "4.1.0"

  acl                      = "private"
  force_destroy            = true
  attach_policy            = true
  policy                   = data.aws_iam_policy_document.urls_s3_policy.json
  control_object_ownership = true
  object_ownership         = "BucketOwnerPreferred"

  tags = merge(
    var.common_tags,
    {
      Name  = "${var.project}-Client-URLs-S3-Bucket"
      Stack = "Backend"
    }
  )
}

I also tried to make the bucket website hosting:

module "urls_s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "4.1.0"

  acl                      = "private"
  force_destroy            = true
  attach_policy            = true
  policy                   = data.aws_iam_policy_document.urls_s3_policy.json
  control_object_ownership = true
  object_ownership         = "BucketOwnerPreferred"
  website = {
    index_document = "index.html"
    error_document = "error.html"
  }

  tags = merge(
    var.common_tags,
    {
      Name  = "${var.project}-Client-URLs-S3-Bucket"
      Stack = "Backend"
    }
  )
}

enter image description here

But it didn't help, the behavior is the same

1

There are 1 best solutions below

4
HSchmale On

You'll need to inspect the object properties to make sure the header was set. It could also be that you didn't enable website hosting on the bucket and didn't link to the right location.

Double check the meta data on your created object. Specifically this key x-amz-website-redirect-location

https://docs.aws.amazon.com/AmazonS3/latest/userguide/how-to-page-redirect.html#redirect-requests-object-metadata