'How to access host in lambda behind both API gateway and cloudfront?

I have a lambda function being executed by an API gateway. I have cloudfront pointing traffic to the API gateway endpoint.

How do I access the host/domain the client is on in my lambda function?

Can I move the Host header to X-Forwarded-Host?

e.g.

abc.com (cloudfront) -> API gateway -> lambda (Host: abc.com)



Solution 1:[1]

In order to propagate Host header through Cloudfront and API Gateway, follow these steps:

Configure Cloudfront to forward Host header

Step-by-step guide

Key points:

Choose the Behaviors tab, and then choose the path that you want to forward the Host header to.

Choose Edit.

Under Cache key and origin requests, confirm that Legacy cache settings is selected. If it's not selected, then follow the steps in the preceding section to create a cache policy. If Legacy cache settings is selected, then complete the following: For Headers, select Include the following headers. From the Add header dropdown list, select Host.

Configure API Gateway request to relay Host header

Detailed docs here

Key point:

Edit your API Gateway resource(s) and for each method you need the Host header edit the Method Request by adding Host header in the HTTP Request Headers list.


You can also move the Host header to X-Forwarded-Host using a Cloudfront function but you would still need to follow the steps above to propagate X-Forwarded-Host header. You can try this out starting with this sample function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tasos P.