rinesh
rinesh

Reputation: 327

Serving gzip and br files from cloudfront and s3

S3 + Cloudfromt is not serving .gz /.br static file when client request header contains Accept-Encoding: gxip, deflate, br.

  1. Compressed file at build time and s3 folder contains index.html, index.html.gz and index.html.br
  2. Added Accept encoding in whitelist header of cloudfront.
  3. Added Content-Length in S3 CORS configuration
  4. Added Content Encoding for index.html.gz as gzip and index.html.br as br with Content-Type as text/html
  5. Disabled Automatic compression in cloufront

But i am not getting compressed files from S3+ cloudfront. I am able to access index.html.gz directly. but cloudfront+S3 not able to serve the file automatically. Am i missing something? Or is it not possible to serve like this?

Upvotes: 3

Views: 3000

Answers (1)

Nikita Kosych
Nikita Kosych

Reputation: 121

This can be done with CloudFront -> Lambda@Edge (Origin request) -> S3. Since this question was asked, AWS added Accept-Encoding header to be passed to S3, so the Lambda function can use it.

The lambda will take the accept-encoding header, check if brotli is in it, and if so, it will add the needed extension to the request that goes to S3 bucket. The clients can still go to the same URL but will get different results based on that accept-encoding header.

Also, make sure that your CloudFront Cache Policy is based on the accept-encoding header.

Example code for Lambda:

'use strict';

/**
 * Funciton registered on 'Origin Request' CloudFront Event
 */
exports.handler = (event, context, callback) => {
  const request = event.Records[0].cf.request;
  const headers = request.headers;
  var isBr = false;
  
  
  if(headers['accept-encoding'] && headers['accept-encoding'][0].value.indexOf('br') > -1) {
    isBr = true;
  }
  const gzipPath = '.gz';
  const brPath = '.br';

  /**
  * Update request path based on custom header
  */  
  request.uri = request.uri + (isBr ? brPath : gzipPath);
  callback(null, request);
};

Upvotes: 2

Related Questions