I' m trying to get real ip addresses of users who visit the site. For that, I'd like to add custom authorization for API service. Using headers for both cases seems like a good idea.
The problem is that I cannot get custom headers in my flask app that is served by nginx and gunicorn web-servers. Getting 'remote_addr' headers returns only 127.0.0.1 IP address despite the fact I post from outer network, not from localhost.
Here are my configuration files:
part of nginx config //1.14.2
location / {
# forward application requests to the gunicorn server
proxy_read_timeout 30s;
proxy_send_timeout 30s;
proxy_connect_timeout 30s;
proxy_pass http://127.0.0.1:5000;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
add_header CLIENT-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
part of gunicorn config //20.0.4
[program:wapp]
command=/home/deeslo/processor/venv/bin/gunicorn -b localhost:5000 -w 4 microservice:app
directory=/home/deeslo/processor
user=deeslo
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
When I check headers, I don't see there neither X-Real-IP/CLIENT-IP from nginx nor other custom headers that I sent in flask make response headers.
What did I miss? Could not solve it yet.
Oh, that was totally my fault.
The problem was I was debugging the application in my IDE where the application was running through embedded web-server, not nginx.
The solution above works perfect, I can get User IP address in flask app with:
request.header['X-Real-IP']