Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda@Edge append querystring to response

Short Overview.

I host an Angular Application on an S3 Bucket. I also got an Cloudfront distribution to handle HTTPS and Redirects.

I try to form an querystring parameter depending on which URL the user is connecting to.

2 examples

test.example.com --> example.com?id=test
hello.example.com --> example.com?id?hello

So far i tried to implement an AWS lambda@Edge Function but nothing worked so far. If i try to manipulate the request it wont have any effects, if i try to manipulate the response the redirect does not work and i get an S3 bucket error or Cloudfront error.

'use strict';
const remove_suffix = '.example.com';
exports.handler = (event, context, callback) => {
    const request = event.Records[0].cf.request;
    const headers = request.headers;
    const host_header = headers.host[0].value;

    if(host_header.endsWith(remove_suffix)){
        request.querystring = 'id=' + host_header.substring(0,host_header.length - remove_suffix.length);
    }

    return callback(null,request);
};

1) Which trigger should I use?

2) Which settings could I be missing on Cloudfront settings?

3) Is my Lambda function wrong?

like image 671
sHamann Avatar asked Sep 17 '25 12:09

sHamann


1 Answers

You may want to ensure, that in the Cloudfront distribution Behavior settings, option Query String Forwarding and Caching is not set to None (Improves Caching)

You can find more info regarding that option in the documentation.

like image 176
antonku Avatar answered Sep 20 '25 06:09

antonku