An AWS API Gateway proxy resource can be configured to respond to requests using a proxy integration to invoke a Lambda function.
From Set up a Proxy Integration with a Proxy Resource:
With this integration type, API Gateway applies a default mapping template to send the entire request to the Lambda function and transforms the output from the Lambda function to HTTP responses.
This makes it trivial to implement a redirection function for custom short URLs.
Example
This example matches the incoming request URL to a post ID and redirects to the corresponding post URL if found (otherwise a status of 404 is returned). It is based on the code that handles the /b short URLs for this blog (ex. https://atj.me/b904).
Depending on your requirements, the function could get the corresponding URL any number of ways (calculate it, look it up in a database, etc). I elected to load key/value pairs from a JSON file that is easily generated with Hugo (which is used to build this blog).
public/index.json
|
|
ShortUrl.js
|
|
Hugo
To create a JSON file containing a key/value pair for each post in Hugo:
- Enable the JSON output in config.toml
[outputs]
home = [ "HTML", "RSS", "JSON"]
- Create a layouts/index.json file that outputs a row for each page in the
posts
section that hasid
defined in the frontmatter.
|
|
This causes public/index.json to be generated which can be bundled with the Lambda function code using webpack.