Passing X-Forwarded-Host and X-Forwarded-Port headers from API Gateway

0

Hi Team, I need to pass the X-Forwarded-Host and X-Forwarded-Port headers from API gateway to the back-end hosts which are behind load balancer. Appreciate if somebody could guide a step-by-step approach.

2 Answers
4
Accepted Answer

Hello!

I’m not an expert on this, but if you’re using an Application Load Balancer, have you checked the settings section?

  1. Go to Load Balancers in the EC2 AWS Console.
  2. Select your ALB and click on Actions and then Edit Load Balancer Attributes.
  3. Look for the X-Forwarded-For header field.
  4. You’ll also find options like Client Port Preservation and Preserve Host Header - these might be helpful for your setup.

Hope this helps! 😊

profile pictureAWS
EXPERT
answered 6 months ago
profile picture
EXPERT
reviewed 6 months ago
1

To pass the X-Forwarded-Host and X-Forwarded-Port headers from API Gateway to your backend hosts behind a load balancer, you can follow these steps:

  1. In API Gateway, go to the Method Request configuration for the relevant API method.

  2. Under HTTP Request Headers, add two new headers: 'X-Forwarded-Host' and 'X-Forwarded-Port'.

  3. Next, go to the Integration Request configuration for the same API method.

  4. In the HTTP Headers section, you'll need to map these headers. Add two new mappings:

    • For X-Forwarded-Host, set the header name (left column) to 'X-Forwarded-Host' and the mapping value (right column) to 'method.request.header.X-Forwarded-Host'
    • For X-Forwarded-Port, set the header name to 'X-Forwarded-Port' and the mapping value to 'method.request.header.X-Forwarded-Port'
  5. Save your changes in API Gateway.

  6. Deploy your API to make these changes effective.

By following these steps, API Gateway will pass the X-Forwarded-Host and X-Forwarded-Port headers to your backend services. The load balancer in front of your backend hosts should then forward these headers to the actual host servers.

It's worth noting that if you're using an Application Load Balancer (ALB), you may need to configure it to preserve these headers. By default, ALBs add their own X-Forwarded headers, which could overwrite the ones from API Gateway. To preserve the original headers, you can modify the load balancer attributes using the AWS CLI or console to set the 'routing.http.xff_header_processing.mode' to 'preserve'.

Remember to ensure that your backend application is configured to read and process these headers as needed.
Sources
how to pass the original url from API Gateway to the backend service | AWS re:Post
Listeners for your Application Load Balancers - Elastic Load Balancing

profile picture
answered 6 months ago
profile picture
EXPERT
reviewed 6 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions