简体   繁体   中英

Apache: How to write X-Forwarded-For with load balancer and 2 servers?

I have a load balancer and two servers. I want to add X-Forwarded-For in my apache so that I can see the IP of the request as opposed to seeing the load balancer IP for every request. How would I do this? I looked it up and X-Forwarded-For: client, proxy1, proxy2 looks like a solution. Would client be the load balancer IP, proxy1 be Server 1's IP, and proxy2 be Server 2's IP?

I assume you already referenced http://en.wikipedia.org/wiki/X-Forwarded-For - which is likely where you copied your X-Forwarded-For: client, proxy1, proxy2 format from.

I also assume you're using a dedicated load balancer (something other than Apache HTTPD), which directs traffic to your "servers" - with your "Apache" included on each server, and that you know how to configure your load balancer to pass this header.

I think the missing piece that you need to understand is this (also from the Wikipedia page):

where the value is a comma+space separated list of IP addresses, the left-most being the original client, and each successive proxy that passed the request adding the IP address where it received the request from. In this example, the request passed through proxy1, proxy2, and then proxy3 (not shown in the header). proxy3 appears as remote address of the request.

IE, if your load balancer is the only proxy that a given request goes through (at least, the only one that adds a X-Forwarded-For header), then the header will only include one value - that of your load balancer.

Assume you are handling a request from a client with 203.0.113.1, and that request comes through your load balancer that has an IP of of 192.0.2.1. Your Apache HTTP instance running on one of your 2 servers should then see the request as coming from 192.0.2.1, with: X-Forwarded-For: 203.0.113.1 .

In order to see this header in your Apache HTTPD logs, you need to use something like this:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %D \"%{Host}i\" \"%{X-Forwarded-For}i\"" custom

The load balancer's IP (192.0.2.1) will still show as the 1st field ( %h ) in the log entry, but the last field ( \\"%{X-Forwarded-For}i\\" ) will contain the client's IP(s) - in this case, 203.0.113.1 . If the client is behind additional proxies that also report X-Forwarded-For , then will be a comma-separated list - with the left-most address being the "closest" to your servers - IE, the one that your load balancer received the request from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM