Table of Contents
If you've migrated from one domain to another and you want to redirect all incoming requests from the old domain to the new one, you'd typically do the following:
- Create a webserver with either Apache or NGINX that listens to incoming requests.
- Rewrite all requests to the new domain while passing appropriate headers (
302HTTP status with a
This works fine except you have to run a whole webserver just to manage this.
We could use API Gateway as an entrypoint for requests and map those requests to our Lambda function. This way, we utilize a resource only when it's needed. Lambda is ideal for this use case since this is not a long lived process and it's also very specialized and the behaviour well defined.
We've used CloudFormation to define our Lambda functions and in the function definition, we've specified that requests coming into API Gateway would act as a trigger for our Lambda functions. We've also specified that GET requests are handled by one function and all other HTTP methods are handled by another.
Finally, we use AWS SAM to package and deploy our code.
- MyRedirectorBucket is the name of the bucket we'll be uploading our packaged Lambda code to.
- Redirector is the name of our CloudFormation stack.
- http://example.org/ is the new domain we are redirecting to.
Make sure our S3 bucket exists, if not, create it
aws s3 ls s3://MyRedirectorBucket/ > /dev/null 2>&1 || aws s3 mb s3://MyRedirectorBucket
Validate our CloudFormation template to make sure there are no errors
aws cloudformation validate-template --template-body file://./app_spec.yml
Package and upload local artifacts to S3
aws cloudformation package \ --template-file app_spec.yml \ --output-template-file packaged.yml \ --s3-bucket MyRedirectorBucket
Deploys the CloudFormation template by creating and executing a changeset.
aws cloudformation deploy \ --template-file packaged.yml \ --stack-name Redirector \ --capabilities CAPABILITY_IAM \ --parameter-overrides \ NewDomain=http://example.org \ HTTPResponse=301
||The HTTP response to redirect with. Only
||New domain to redirect to.|
Deleting a Stack
While testing, you may need to delete a stack
aws cloudformation delete-stack --stack-name Redirector
Since we are using AWS SAM, we are going to run into bug #191. If you look at the Stages in your API Gateway, you're going to see a stage named
Stage. Hopefully this bug is fixed soon.
Copyright 2018 by Modus Create, Inc.
This software is licensed under the permissive MIT License.