djangonginxx-forwarded-for

What's the purpose of setting "X-Forwarded-For" header in nginx


I have the following Nginx configuration for my Django application:

upstream api {
    server localhost:8000;
}

server {
    listen 80;

    location / {
        proxy_pass http://api;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /staticfiles {
        alias /app/static/;
    }
}

I based this config on a tutorial here. After some research, looks like setting the Host header allows the Django API to determine original client's IP address (instead of the IP address of the proxy).

What's the point of the X-Forwarded-For header? I see a field called $http_x_forwarded_for in the nginx logs but I'm not sure it's related.


Solution

  • From the Mozilla docs

    The X-Forwarded-For (XFF) header is a de-facto standard header for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or a load balancer. When traffic is intercepted between clients and servers, server access logs contain the IP address of the proxy or load balancer only. To see the original IP address of the client, the X-Forwarded-For request header is used.

    In fact, I think that you have misunderstood the Host header. My understanding is that it will be the IP of the nginx server.