How to get client IP behind AWS ALB?

该文章根据 CC-BY-4.0 协议发表,转载请遵循该协议。
本文地址:https://fenying.net/en/post/2024/07/10/how-to-get-client-ip-behind-aws-alb/

Today we deployed a new service, behind an AWS application load balancer (ALB). There is an Nginx on every target host, to dispatch requests to each worker process inside the host.

Here is how to configure Nginx to get the real client IP behind AWS ALB.

1. Setup AWS ALB

You need to check the attributes of ALB, ensure the X-Forwarded-For Header is set to Append mode.

Under the Append mode, ALB will append the real client IP to the end of the X-Forwarded-For header, separated by commas.

And there are another two modes:

  • The preserve mode will pass the original X-Forwarded-For header from the client to the backend service, without modification, which allows the client to forge its IP if you trust it.
  • The remove mode will not send the X-Forwarded-For header to the backend service, which means the backend service cannot get any client IP.

2. Configure Nginx to get the real client IP

Add the Real-IP module settings into http.server section of your Nginx configuration, here is an example:

 1http {
 2
 3    server {
 4
 5        # Other configurations omitted, please add them by yourself...
 6
 7        # Fetch the last IP address from X-Forwarded-For, and put it into $remote_addr
 8        real_ip_header X-Forwarded-For;
 9
10        # Only do this if the requests are sent from the CIDR of your VPC.
11        # Not necessary if you have security groups to restrict the port only accessible from ALB.
12        # Anyway, if you turn this on, you have to change it to your VPC CIDR, or the exact CIDR of ALB.
13        set_real_ip_from 172.31.0.0/16;
14
15        # Other configurations omitted, please add them by yourself...
16    }
17}

Now, just add the mapping of $remote_addr to another header in location.

1location / {
2
3    proxy_pass http://backend;
4
5    # Overriding X-Forwarded-For with value of $remote_addr
6    proxy_set_header X-Forwarded-For $remote_addr;
7}

References

comments powered by Disqus

Translations: