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.


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.


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


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 :)

  • Great idea, didn't think of doing the redirect in the function. – Emile Petrone Jan 7 at 21:09

I think there is a setting at cloudfront to do this. Either that or use lambda@edge — so you’re not creating ‘real’ lambdas.

The other option, which I personally use, is put a Cloudflare in front of your cloudfront distribution — sure it’s two CDNs, but Cloudflare can do these redirects pretty darn easily.

The other option is to create two cloudfront distributions, one for www and one for non-www but both end up at the same API Gateway. Not ideal, as caching benefits will be limited, but it would work.

Your Answer

