set_real_ip_from behavior

Andrei lagged at
Tue Jul 2 09:12:22 UTC 2019


I'm having some issues with getting X-Forwarded-For set consistently for
upstream proxy requests. The server runs Nginx/OpenResty in front of
Apache, and has domains hosted behind Cloudflare as well as direct. The
ones behind Cloudflare show the correct X-Forwarded-For header being set,
using (snippet):

http {
real_ip_header X-Forwarded-For;
server {
location ~ .* {
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;

However, when I receive a direct request, which does not include
X-Forwarded-For,  $http_x_forwarded_for, $proxy_add_x_forwarded_for,
$http_x_real_ip are empty, and I'm unable to set the header to $remote_addr
(which shows the correct IP). If I try adding this in the server {} block:

if ($http_x_forwarded_for = '') {
    set $http_x_forwarded_for $remote_addr;

I get:

nginx: [emerg] the duplicate "http_x_forwarded_for" variable in
nginx: configuration file /usr/local/openresty/nginx/conf/nginx.conf test

The above works to set $http_x_real_ip, but then I end up with direct
connections passing Apache the client IP through X-Real-IP, and proxied
connections (from Cloudflare) set X-Forwarded-For.

The log format I'm using to verify both $http_x_forwarded_for and
$http_x_real_ip is:

log_format json_combined escape=json
    '"status": "$status",'

How can I consistently pass the backend service an X-Forwarded-For header,
with the client IP, regardless of it being a direct request or proxied
through Cloudflare/some other CDN?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the nginx mailing list