AWS Route53 & Lambda – Redirect Naked HTTP to HTTPS WWW for Serverless Apps

amazon-lambdaamazon-route53amazon-web-servicesdomain-name-system

Problem

I have a site running on a 'serverless' AWS Lambda function. Route53 routes requests to the API Gateway which connects to the Lambda function.

The problem with this is that you can't setup traditional server redirects.

Example

As an example, I followed this question/answer to route http://<my_domain>.com to https://www.<my_domain>.com, I'm using an A record alias to S3 bucket that is setup as a Static site redirect to https://www.<my_domain>.com.

Question

How can I get https://<my_domain>.com to redirect to https://www.<my_domain>.com in a serverless environment like Lambda?

Best Answer

You will have to perform the redirect in your lambda function.

I’m sure the actual hostname used in the URL is passed to the Lambda, perhaps as event.headers.Host. So in your Lambda you’ll have to do something like this python-like code:

def lambda_handler(event, context):
    if not event['headers']['Host'].startswith('www'):
        return PermanentRedirect('www.'+event['headers']['Host']+event['path'])

However if I were you I would point the non-www hostname to a different API gateway with a single Lambda dedicated to performing the redirect to www. Then in your actual worker lambdas you won’t have to worry about the redirects.

Hope that helps :)

Related Topic