DEV Community

Cover image for How to do a (serverless) web redirection in AWS Route53?
Sonny Alves Dias
Sonny Alves Dias

Posted on • Updated on • Originally published at Medium

How to do a (serverless) web redirection in AWS Route53?

Imagine you are using a DNS provider and you have a domain example.com and example.net redirecting to example.com. It's pretty easy to set up.

One day you migrate to AWS Route53 because you want geolocation, load balancing, or something of the sort. And disaster! There is no web redirection.

With this article, you will know how to solve that and set up a serverless web redirection at a low cost and a little effort.

Steps

1. Lambda

Please find below an example of a NodeJS lambda:

export const handler = async(event) => {
    const res = {
        statusCode: 301,
         headers: {
            Location: 'https://example.com'
        }
    };
    return res;
};
Enter fullscreen mode Exit fullscreen mode

and Python

def lambda_handler(event, context):

    return {
        "statusCode": 301,
        "headers": {
            'Location': "https://example.com"
        }
    }
Enter fullscreen mode Exit fullscreen mode

2. API Gateway

  • Select a REST API (*not Private *)
  • In the next page,
    • confirm REST API, not Websocket
    • create a New API
    • give it a name like web-redirection
    • endpoint type select Edge Optimized
  • In the API detail page,
    • Click on Actions and select Create Method
    • Select GET method under the path / and confirm
  • In the / GET method details,
    • Select the lambda you created in the first section and save.
  • Finally, publish the API by clicking on Actions > Deploy API
    • Enter a stage name for your deployment something like production

3. Custom Domain Name

  • Still in the API Gateway service, click on  Custom Domain Names
  • For each domain you want to redirect, Create a Custom Domain Name
    • Select Edge Optimized to match the API Gateway we created above
    • And select (or create) a certificate that matches the domain
  • Once created, setup API mapping to the API gateway we created before with no path required

4. CloudFront

  • Go to CloudFront and create a distribution
  • Do not define any alternate domain, and no certificate
  • For the origin enter the API gateway endpoint and specify for the origin path /prod as the stage name you defined earlier

5. Route53

  • Add a Route53 record on the domain
  • And point at the CloudFront from the previous section

Conclusion

Go to your domain example.net and validate that the redirection to example.com is working!

Top comments (0)