I have the following server configuration:

Django App - Gunicorn - Nginx

Nginx directs incoming requests to the gunicorn instance. The site can be reached directly, or through redirects from other domains. To clarify:

App is hosted on api.myapp.com

  • Some clients directly issue requests to api.myapp.com
  • Some clients issue requests to someotherdomain.com, which is also controlled by me. In the nginx config for someotherdomain.com, I forward requests to api.myapp.com with proxy_pass

In this setup, I want to be able to get end users IP address. I have the following directives nginx conf for api.myapp.com

set_real_ip_from my_ip;
real_ip_header X-Forwarded-For;
real_ip_recursive on;     

With these directives, X-Real-IP header is set correctly when requests come from redirects, but is is not set at all when requests directly come to api.myapp.com, and I'm kinda confused here. I've tried several other configurations with no success. What can I do to be able to get user's real ip in cases of redirects and directs acccesses?

  • “I redirect request to” — is it real HTTP redirect or you mean proxy_pass? Or something else? – Alexey Ten Nov 8 '17 at 5:29
  • It is proxy_pass, I've updated the description – Ozgur Akcali Nov 8 '17 at 9:46

When client requests come directly to api.myapp.com the HTTP headers are set by the actual client making the request. Unless the clients have been configured to set up the X-Forwarded-For HTTP header, there won't be such a header.

Now, the purpose of nginx set_real_ip feature is to make nginx think that the request actually comes from the IP address specified in the header, not from the IP address from the TCP socket.

So, the overall effect of this that nginx internal remote IP variable always has the actual client IP address. The IP address is the content of X-Forwarded-For HTTP header if it exists and if the source IP matches the allowed list. Otherwise it is the TCP socket's remote IP address.

This remote IP address is then used in log files, passed to applications, etc.

So, to fix your issue, you need to fix your code to use the nginx provided remote IP address.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.