CloudFront with multiple origins and behaviors and Lambda@Edge

Can I use a single CloudFront web distribution to serve content from multiple origins using multiple Behaviors?
yes its possible, Say for example s3 origins and API gateway origins can be configured in single cloudfront.
Cloudfront
It helps to deliver content, including web pages, videos, applications, and APIs, to end-users with low latency, high transfer speeds, and reduced load times.
Components of Cloudfront
Origin server — its a source location where cloudfront gets content and serves the users
Behaviour -configuring behaviors in CloudFront is essential for tailoring how the content is cached, served, and protected ,that is it defines rules on how CloudFront will serve the content ,cache the content and which origin servers it will get the content from. This includes url path patterns (/static/*, /myapicontextpath/*), HTTP methods, and specific headers or query strings.
it helps to route requests to appropriate origins if multiple origins are configured in cloudfront. when having multiple origins having unique url path pattern for each origin is mandatory. Same url path pattern behaviour cannot be mapped to different origins it wont give to desired routing
let us consider below origins and behaviours
Origins
origin 1- s3 bucket — sampleangularapp1 (bucketname)
origin 2- s3 bucket — sampleangularapp2 (bucketname)
origin 3- api1— myapi1.pub.example.com (api public custom domain)
origin 4- api 2— myapi1.pub.example.com (api public custom domain)
Behaviours
Behaviour 1- origin 1 -url path pattern /app1ui/*
Behaviour 2- origin 2-url path pattern /app2ui/*
Behaviour 3- origin 3-url path pattern /apicontextpath1/*
Behaviour 4- origin 4-url path pattern /apicontextpath2/*
default Behaviour - origin 1 -url path pattern /app1ui/*
Note: default Behaviour is mandatory in Cloudfront based on requirement we can use default behaviour to handle requests (route to particular origin)
Cache setting
- Static content like images, CSS, and JavaScript files can be cached with a long TTL to minimize origin requests.
- Dynamic content like API responses can have a shorter TTL or no caching to ensure users always get the latest data.
Cache invalidation
When ever s3 content origin is updated — cloudfront invalidation is required to get the updated content. Basically cache invalidation allows us to remove objects from CloudFront edge caches before they expire.
Failover origins
Through origin group we can achieve active passive failover. Origin group includes two origins (a primary origin and a second origin to failover to) and a failover criteria.
If the primary origin is unavailable or returns specific HTTP response status codes that indicate a failure, CloudFront automatically switches to the secondary origin. failover criteria can be HTTP 4xx and 5xx Status codes.
CloudFront fails over to secondary origin only when the HTTP method request is GET, HEAD, or OPTIONS. CloudFront does not failover when the HTTP request is POST, PUT, etc.(other than GET,HEAD and OPTIONS)
Lambda edge
Lambda edge can be configured on each behavior and Lambda edge is used for providing authentication and also it can be used to manipulate the request headers , request uris , set security response headers if required
async function handler(event) {
const response = event.response;
const headers = response.headers;
// Set HTTP security headers
// Since JavaScript doesn't allow for hyphens in variable names, we use the dict["key"] notation
headers['strict-transport-security'] = { value: 'max-age=63072000; includeSubdomains; preload'};
headers['content-security-policy'] = { value: "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'; frame-ancestors 'none'"};
headers['x-content-type-options'] = { value: 'nosniff'};
headers['x-frame-options'] = {value: 'DENY'};
headers['x-xss-protection'] = {value: '1; mode=block'};
headers['referrer-policy'] = {value: 'same-origin'};
// Return the response to viewers
return response;
}
Event Types
Lambda@Edge functions can be triggered by four types of CloudFront events:
- Viewer Request: Triggered when CloudFront receives a request from a viewer before checking the cache. use case -Authentication logic can be set at viewer request
- Viewer Response: Triggered before CloudFront returns the response to the viewer.
- Origin Request: Triggered before CloudFront forwards a request to the origin server. use case -url manipulation logic can be done here
- Origin Response: Triggered when CloudFront receives a response from the origin server.
Viewer request is invoked before origin request.
Lambda@edge would get invoked for all request including static files like css ,woff files which will create lot of 302 rediretcs to avoid that By selectively bypassing authentication for static assets in Lambda@Edge function, we can prevent unnecessary invocation of authentication logic for requests that do not need it. This improves performance.