0

I have the following nginx configuration in docker. The problem is in my node app (backend proxy) I get an IP of nginx server, not the user real IP when sending requests from frontend using X-Real-IP headers or X-Forwarder-For

upstream frontend {
    server frontend:3000;
}

upstream backend {
    server backend:4000;
}

server {
    listen 80;
    location / {
        auth_basic "Restricted";
        auth_basic_user_file  /etc/nginx/.htpasswd;

        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 1m;
        proxy_connect_timeout 1m;
        proxy_pass http://frontend;
    }

    location /api {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Real-IP $remote_addr;

        rewrite /api/(.*) /$1 break;
        proxy_pass http://backend;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    location /socket.io/ {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;

        proxy_pass http://backend;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
3
  • Capture HTTP packets in and out and then use a tool like Wireshark to analyze the headers. Commented Dec 2, 2024 at 21:38
  • You are most probably use a bridge network, which is default for docker networking. AFAIK, for being able to get the real remote client address, you need to use either host or macvlan network for your docker container. Or you can run nginx directly on your host, dockerizing only the backend app(s). Commented Dec 3, 2024 at 1:37
  • Instead of using the rewrite /api/(.*) /$1 break; directive, a more efficient way would be to strip the /api prefix using the URI part on the backend proxy_pass argument: location /api/ { ... proxy_pass http://backend/; ... } (note the location prefix change and the trailing slash after backend). Commented Dec 3, 2024 at 14:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.