Nginx – in nginx, how can I return a http 500 return code and include response body in response to client

nginx

We have a customer requirement to return an http 500 response code to their client for a request for something that is not found and also pass the response body from the application server. Their app will not accept a 404 return code. We have a kind of hack to try to return this code through nginx and still have other cases of valid 500 responses try the next upstream server. For the special case that our customer wants, we are returning a 501 from the upstream server and then using proxy_intercept_errors and error_page directives as follows:


server {
listen 28080;
#In comming
server_name INTO;

    location / {
        proxy_pass http://some_servers;
        proxy_redirect          off;
        proxy_next_upstream     error timeout invalid_header http_500 http_404;
        proxy_connect_timeout   2;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_intercept_errors  on;
    }


    # redirect server error pages to the static page /50x.html
    #
    error_page   501 =500  /50x.html;
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

When we do this, we get the response code they require (500), but we lose the response body. Is there some way to do this, ie, send back a phony return code that the nginx converts to a 500 and the response body passed from the server is included in the response to the client. I am fairly new to nginx and have been researching and trying for a couple of days with no luck. I think maybe this can be done with proxy_set_header or using rewrite. If anyone knows how to do this, could you give a detailed example please.

Best Solution

Could you return your response body as a string?

error_page 404 = /404.html;

location /404.html {
    return 500 "<b>Whoa! 500 couldn't find it.</b>
";
}
Related Question