This code ensures X-Forward (and friends) headers are updated correctly when using stacked proxies: the host, protocol and "for" should be inherited from the previous proxies.
Of course, there are 3 competing/similar ways to retrieve this information from the previous Proxy, so this tries to be compatible with them all:
Forwarded
(new, nicer and standardized in rfc7239)X-Forwarded-[For/Host/Proto]
, the legacy but de-facto standardX-Real-IP
, a less-common alternative to X-Forwarded-For[0].
Also, retrieving them from the incoming request requires caution: Malicious clients may try inject these headers, so these headers should only be used when we expect them.