0

I have a basic django application setup under nginx. So far everything runs fine. What I need is a setup so I can handle 404s under /media/ with my proxy_pass application. Currently, it shows a bare nginx 404 error when no file is found. I've read https://nginx.org/en/docs/http/ngx_http_core_module.html#location, but cannot get my head around to find out how.

Two links, to showcase: https://pfadi.swiss/de/what/ (showing my real 404) and https://pfadi.swiss/media/foooing/ (showing nginx simplicity).

The reason: I need to intercept 404 errors under /media/ so I can redirect with the django application, if needed.

server {
    listen 127.0.0.1:123455;
    root /mysite;
    server_name
        host.com
        ;

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;
        if (!-f $request_filename) {
            proxy_pass      http://upstream_name ;
            break;
        }
    }

    error_page 500 502 503 504 /nginx/50x.html;
    location /nginx/ {
        root    /mysite/public/static/;
    }

    location /media/ {
        alias   /mysite/public/media/;
        expires 3M;
    }

}
benzkji
  • 101
  • 3

1 Answers1

0

As easy as it gets, reading on and on. coming across this: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#when-does-location-block-evaluation-jump-to-other-locations

So, basically, first try the public folder, if no match, @proxy_pass fallback.

    location / {
        root /mysite/public;
        try_files $uri @proxy_pass;
        expires 3M;
    }
    location @proxy_pass {
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;
        proxy_pass      http://upstream_server ;
    }
benzkji
  • 101
  • 3
  • 1
    You don't need a regex here, just use `location / { ... }` instead of `location ~ / { ... }`. And you don't need `if (!-f $request_filename) { ... }` check too, this check is already done by `try_files` directive, leave only the `proxy_pass http://upstream_server;` line. – Ivan Shatsky Jul 03 '20 at 09:55
  • yes, all updated. thx. – benzkji Jul 03 '20 at 22:31