4

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?

sHamann
  • 789
  • 3
  • 10
  • 36

1 Answers1

4

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.

antonku
  • 7,377
  • 2
  • 15
  • 21
  • thx for the advice. I get the folliwing error `502 ERROR The request could not be satisfied. The Lambda function result failed validation: The function tried to add, delete, or change a read-only header. ` You mind to help me with this one? – sHamann Jul 11 '19 at 09:23
  • Were there any changes in the code posted in the question? As I can see the original headers object is not modified there. And according to the examples in the documentation it is perfectly valid to overwrite `request.querystring`: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-query-string-examples – antonku Jul 11 '19 at 09:28
  • The code i posted is still the same. Im currently using the `Viewer Response` Trigger. – sHamann Jul 11 '19 at 09:32
  • Okay, I would try to change the trigger to `Viewer Request` to see if that makes any difference. – antonku Jul 11 '19 at 09:33
  • Now i get redirected to the s3 bucket but without any querystrings which i can access – sHamann Jul 11 '19 at 09:39
  • Wow, that was easy! Thanks! – Mars Aug 04 '20 at 13:44