nginx error_page for 502 Bad Gateway errors

Solution 1:

I did this for the whole vhost:

server {
         (...) 
         error_page 500 502 503 504 /5xx.html;
            location /5xx.html{
                    root /www/error_pages/;
         } 
}

This works perfectly for me.

Solution 2:

Try setting proxy_intercept_errors on; https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_intercept_errors

Solution 3:

The devils in the details; my @maintenance named location was not setup correctly. Specifically, the send argument ($uri/) to try_files was causing the problem. Here is the correct named location:

location @maintenance { 
    root /path/to/static/offline/files;
    try_files $uri /index.html =503;
}