Add content-type for specific file types in Amazon CloudFront?


I have an S3-bucket, that I’m serving using CloudFront. And I want to serve some JSON-files from it.

Out of the box, the CF response doesn’t contain any Content-Type headers at all for this file type. The file is just downloaded by the browser as any regular file. However, I want it to have a proper mime type header: Content-Type: application/json.

I know, I can set custom header for any single file manually in S3, however, is it possible to specify some rule for specific filename extensions to add specific HTTP headers to the response in Amazon CloudFront?


Update: CloudFront itself does not provide a built-in mechanism for manipulating headers, but Lambda@Edge, used in conjunction with CloudFront, provides a mechanism to create hooks that can examine and modify origin response headers. It can’t actually examine the response body, but can inject static or heuristically-derived headers. This is potentially a viable workaround if the content is from a known/trusted source and the content-type is known, but should probably not be used for user-submitted content, since an incorrect content-type could cause a browser to misinterpret the payload, and might be a potential exploit vector. Setting the content-type on the object, correctly, when it is uploaded is probably still the better solution.

The original answer here pre-dates Lambda@Edge and refers to native capabilities of CloudFront itself.

CloudFront uses the response headers provided by the origin server, whether it’s S3 or a custom origin. CloudFront does not provide a mechanism to rewrite them or to add them.

The solution is to set the Content-Type on the object when originally uploading it into S3.

If you upload the file to S3 with Content-Type set, the same value will be returned when the object is downloaded (whether directly from S3 or through CloudFront). Otherwise, you have to modify objects after upload if you don’t want the default Content-Type: binary/octet-stream header that S3 assigns when you don’t specify one.

Leave a Reply