Sai Umesh

CloudFront URL redirects and Authentication using CloudFront functions

2 min read

AWS CloudFront is a highly popular service provided by Amazon Web Services (AWS). It enables you to efficiently distribute various types of content, such as videos, audios, and static content, like a web application.

Though CloudFront content is static, we can change its behavior using CloudFront functions. functions can manipulate the requests and responses that flow through CloudFront, perform basic authentication and authorization, generate HTTP responses at the edge. The CloudFront Functions runtime environment offers sub millisecond startup times, scales immediately to handle millions of requests per second, and is highly secure.

CloudFront Functions is ideal for lightweight, short-running functions for use cases like the following:

Header manipulation

You can insert, modify, or delete HTTP headers in the request or response. For example, you can add a True-Client-IP header to every request Example

Status code modification and body generation

You can evaluate headers and respond back to viewers with customized content.

Request authorization

You can validate hashed authorization tokens, such as JSON web tokens (JWT), by inspecting authorization headers or other request metadata - Example

URL redirects or rewrites

URL redirects or rewrites – You can redirect viewers to other pages based on information in the request, or rewrite all requests from one path to another. Example - 1 Example - 2

Sample code for re-writing url

The below example appends index.html to Uri when its missing a filename.

function handler(event) {
  var request = event.request;
  var uri = request.uri;

  // Check whether the URI is missing a file name.
  if (uri.endsWith("/")) {
    request.uri += "index.html";
  } // Check whether the URI is missing a file extension.
  else if (!uri.includes(".")) {
    request.uri += "/index.html";
  }

  return request;
}

image info

Source

You can find more information on CloudFront functions here


Sai Umesh

I’m Sai Umesh, a software engineer based in India. Working as a DevOps engineer.