Editable URL Rewrite Map for CloudFront/S3 Website using Lambda@Edge

301-redirectamazon s3amazon-cloudfrontamazon-lambdarewrite

I'm migrating a static website from IIS to Amazon S3, using CloudFront for https. The old site used the URL Rewrite module and had 301 redirect maps with over 200 entries. Here is an example:

example.com?pageID=1234 => example.com/about/history

I want to make sure that all the redirects are migrated with the website. Many of the entry keys include query strings, so I don't think S3 XML redirection rules or object metadata redirects will work for them (correct me if I'm wrong).

I want to use a CloudFront user request event trigger with a Lambda@Edge function to create a rewrite map of key-value pairs (something like what is described in this guide). The function would grab the request URI and, if it matches any of the keys in the map, change the request to reflect the corresponding value.

I could hard code the rewrite map into the Lambda function, but new entries will be added to the map over time. I would prefer not to create a new version of the function, and then edit the CloudFront behavior to use this new version, whenever a new vanity URL is needed. It feels kind of dangerous and prone to errors that could mess with CloudFront.

Does anyone know of a way to create a rewrite map (a JSON file or something?) that can be attached to a Lambda function and edited without altering the Lambda function itself? Thanks!

Best Answer

I would save the JSON config file in a S3 bucket and made the Lambda@Edge read it upon startup (not for every request though! only once at Lambda start up).

Give the Lambda proper IAM permission to read the file from S3 and you're done.

  • you'll have the config separated from the code
  • no need to re-deploy Lambda or reconfigure CloudFront
  • config changes will propagate globally within minutes (you can configure a config expiration time in the Lambda if you want to re-download it every few minutes)

Hope that helps :)