amazon-web-servicesamazon-s3amazon-cloudfront

Content-Type response header is wrong on S3 with Cloudfront distribution?


I have an S3 bucket, which is behind a Cloud front distribution.

Upon downloading assets, the response header Content-Type seems to be binary/octet-stream. Is there a way I can configure this to be application/octet-stream ?

When I was using NGINX to serve files, this was already done so my application is expecting the latter. Do I just need to configure something?


Solution

  • Yes, you can control the Content-Type header for objects in your S3 bucket that are served through CloudFront. There are a few ways to handle this:

    1. Directly in S3 (Recommended): When uploading objects to S3, set the correct Content-Type metadata. You can do this:

      • Through the AWS Console by editing the object metadata
      • During upload using the AWS SDK
      • Using the AWS CLI with the --content-type parameter:
      aws s3 cp yourfile.bin s3://your-bucket/ --content-type "application/octet-stream"
      
    2. Using CloudFront Functions or Lambda@Edge: If you can't modify the S3 objects directly, you can transform the Content-Type header using:

      • A CloudFront Function (lighter weight, cheaper)
      • Lambda@Edge (more powerful but more expensive)

    Here's a simple CloudFront Function example:

    function handler(event) {
        var response = event.response;
        response.headers['content-type'] = [{value: 'application/octet-stream'}];
        return response;
    }
    
    1. S3 Bucket-wide default: You can also set default metadata for your entire bucket using S3 bucket policies, though this is less flexible.

    The simplest approach is usually to just set the correct Content-Type when uploading to S3. The header will then be passed through CloudFront automatically.