Frontend and backend servers behind Nginx - CORS problem [closed]

Here is a newbie question about having two servers behind nginx.

I have two applications, nextjs frontend, and django backend. Nextjs listens to the port 127.0.0.1:3000, and django serves its api on 127.0.0.1:8000/api. The two apps are behind nginx server, which itself listens at the port 38. The idea is to make the django backend completely inaccessible from the outside.

How do I setup nginx configuration, so that django api sees the nextjs requests as coming from 127.0.0.1:3000, rather than 127.0.0.1:38? I have set up the django CORS_ALLOWED_ORIGINS to "http://127.0.0.1:3000" and would like to keep i that way.

Here is one of the several nginx conf file variants that I tried (none worked)


server {
    listen 38;
    location /api {
        proxy_pass http://127.0.0.1:8000;  # Forward API requests to Django
        proxy_set_header Host $host;  # Preserve the original Host header
        proxy_set_header X-Real-IP $remote_addr;  # Pass the real IP of the client
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  # Pass the forwarded IP
        proxy_set_header X-Forwarded-Proto $scheme;  # Pass the protocol (http or https)
    }

    location / {
        proxy_pass http://127.0.0.1:3000;  # Forward all other requests to Next.js
        proxy_set_header Host $host;  # Preserve the original Host header
        proxy_set_header X-Real-IP $remote_addr;  # Pass the real IP of the client
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  # Pass the forwarded IP
        proxy_set_header X-Forwarded-Proto $scheme;  # Pass the protocol (http or https)
    }   
}

What I keep getting is django receiving header from the port 38:

Firefox developer tools showing request header with the 127.0.0.1:38 address

Any help appreciated.

Back to Top