skip to Main Content

I have an S3 bucket where each folder in the root contains a website with the folder name being the website url. I have a Cloudfront distribution with this bucket as an origin and a Lambda Edge function associated with the distribution for origin requests. In the function I want to take the original requested url and add it to the origin request as the path key for the S3 bucket. How can I do this?

In the event request I see these fields:

'origin': {'custom': {'customHeaders': {}, 'domainName': '<bucketName>.s3-website-us-east-1.amazonaws.com', 'keepaliveTimeout': 5, 'path': '', 'port': 80, 'protocol': 'http', 'readTimeout': 30, 'sslProtocols': ['TLSv1', 'SSLv3']}}, 'querystring': '', 'uri': '/'

I have tried setting the original requested url as the path in [‘origin’][‘custom’], as the querystring or uri, and appending it to the domainName in [‘origin’][‘custom’], but none have worked. Adding as a querystring or uri returned ‘The specified bucket does not exist’, adding as path returned ‘Invalid path’, and adding to domainName returned ‘Invalid domainName’.

Thanks for the help!

2

Answers


  1. Chosen as BEST ANSWER

    The solution to my problem was setting the original requested url (the S3 bucket path) as the uri in the request, as mentioned by @vpereira. In addition, I was getting the original requested url by forwarding the Host Header to the origin request, so I needed to change the host header back to the url for the S3 bucket once I retrieved the original requested url. The second part is described more here.

    Code solution:

    def lambda_handler(event, context):
         request = event['Records'][0]['cf']['request']
         # Get original host header
         requested_url = request['headers']['host'][0]['value']
         # Set original host header as uri
         request['uri'] = '/' + requested_url + request['uri']
         # Set host header to bucket url
         request['headers']['host'][0]['value'] = '<bucketName>.s3-website-<region>.amazonaws.com'
         return request
    

  2. If I understood your question correctly, I think you’re modifying the wrong field.
    The place that needs changing inside of the event is not origin, but request.
    Basically you need to change uri inside of event['Records'][0]['cf']['request'], and then return request

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search