4

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?

2 Answers2

1

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

MLu
  • 23,798
  • 5
  • 54
  • 81
0

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.

keithRozario
  • 146
  • 7