I am trying to pass the request client IP address to a FastAPI backend via Nginx.
Example FastAPI endpoint:
@app.post('/api/example')
def send_order(data: SomeDataType, request: Request, response: Response):
print(request.client.host) # ip address of client
This works fine, until the backend is behind a reverse proxy. (Provided by Nginx.)
Now, it just logs the local IP address as the address of the host. (In this case a 172.X.X.X
type of address.
Here is how I have configured Nginx:
location /api {
proxy_pass http://localhost:5555/api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
I thought this should be enough. I did some futher reading which suggested perhaps I need to add another middleware into the backend. Currently FastAPI is using the CORS middleware, but nothing else.
I’m not sure if this information is correct or not. This is where I got stuck and couldn’t find any examples which I could make sense of.