Nginx – configure nginx to pass redirects through from upstream proxied application

nginxredirectreverse-proxy

I have nginx serving static files and proxying requests for an internal django server. This all works mostly fine, but I have a view which returns a 302 redirect back to the Referer page, effectively doing a browser refresh from a link click.

When not served through nginx, this works and the application returns the 302 with Location header set to the same page, which is what I want.
However, when served through nginx it redirects back to "/". It seems no matter what I try it always does the same.

I have checked that django is receiving the request referer header, which it is. I've tried proxy_redirect commented out, set to off and default and / /. I can't use the latter because it strips the port number which I need at the moment for testing.

Here's my nginx config:

upstream django {
    server unix:/run/waitress/django.sock;
}

server {
    listen 80 backlog=4096;
    server_name www.example.co.uk;
    charset     utf-8;
    client_max_body_size 20M;
    root /var/www/static_public;

    location /media  {
        sendfile on;
        sendfile_max_chunk 500k;
        tcp_nopush on;
    }

    location /static {
        sendfile on;
        sendfile_max_chunk 100k;
        tcp_nopush on;
    }

    # favicon redirect
    location ~ ^/[a-z][a-hj-z][a-z-]+\.(png|xml|ico|json|svg)$ {
        return 301 /static/site/img$request_uri;
    }

    location / {
        proxy_pass          http://django/;
        #proxy_redirect      what do I put here????;
        proxy_set_header    Host $host;
        #proxy_set_header    Referer $http_referer;
        proxy_set_header    X-Real-IP $remote_addr;
        proxy_set_header    X-Forwarded-Proto $scheme;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

nginx is passing the Referer header through without explicitly setting it.

Best Answer

False alarm!

It turns out my django view was returning the "/" redirect due to the referer header not being deemed is_safe_url because of my testing setup :/

proxy_redirect off; is working for me.