Welcome! Log In Create A New Profile

Advanced

combining try_files with proxy_pass

February 23, 2024 08:26AM
Hi,

We have an nginx proxy server running in front of a django website. The proxy is:

proxy_pass http://unix:/run/gunicorn.sock;

It would be very helpful to imitate the try_files directive that's shown in the default vhost:

location / {
try_files $uri $uri/ =404;
}

How can that be done? The files aren't on the local filesystem but are only visible through a proxy.

The following code seems to work.

Attempt #1:

location @django1 {
proxy_pass http://unix:/run/gunicorn.sock;
proxy_intercept_errors on;
recursive_error_pages on;
error_page 404 = @django2;
}

location @django2 {
if ($uri !~* /$ ) {
rewrite ^(.*)$ $1/ ;
}
proxy_pass http://unix:/run/gunicorn.sock;
}

location / {
try_files not_a_file.html @django1;
}

First, it tries the plain file without extension. If that fails, it goes on to @django2 which adds a trailing slash, and tries yet again. Great.

However a small problem with this, is that if it succeeds in retrieving the file with a trailing slash, and returns that to the browser, the browser still believes it's at the original URL. Why does that matter? Usually it doesn't. But some pages in our website send an HTML meta refresh redirect <meta http-equiv="refresh" content="0; URL=../../page2.html">, and that functionality depends on knowing your current URL path, in order to then be redirected to a new path.

So, Attempt #2:

location @django1 {
proxy_pass http://unix:/run/gunicorn.sock;
proxy_intercept_errors on;
recursive_error_pages on;
error_page 404 = @django2;
}

location @django2 {
if ($uri !~* /$ ) {
rewrite ^(.*)$ $1/ redirect;
}
proxy_pass http://unix:/run/gunicorn.sock;
}

location / {
try_files not_a_file.html @django1;
}

The only difference here is to add "redirect" to the rewrite command.

Now the browser will completely redirect to the path with the trailing slash /. A meta refresh redirect will work, after that. It seems to be the final solution.

However, there is a small side-effect. Every 404 error on the website will show a trailing slash, since that's the last page that was tried, before finally giving up.

It's only a detail, but could that side-effect be eliminated somehow? In other words, if the end-user gets a 404, there is no (additional) trailing slash?
Subject Author Posted

combining try_files with proxy_pass

sdarwin February 23, 2024 08:26AM



Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 244
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready