【问题标题】:in nginx, how can I return a http 500 return code and include response body in response to client在 nginx 中,如何返回 http 500 返回码并包含响应正文以响应客户端
【发布时间】:2014-08-05 20:07:29
【问题描述】:

我们有一个客户要求,向他们的客户返回一个 http 500 响应代码,以请求未找到的东西,并从应用程序服务器传递响应正文。他们的应用程序不接受 404 返回码。我们有一种 hack 尝试通过 nginx 返回此代码,并且仍然有其他有效 500 响应的情况尝试下一个上游服务器。对于客户想要的特殊情况,我们从上游服务器返回 501,然后使用 proxy_intercept_errors 和 error_page 指令,如下所示:

server { 听28080; #即将到来 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;
    }

当我们这样做时,我们会得到他们需要的响应代码 (500),但我们会丢失响应正文。有没有办法做到这一点,即发回一个虚假的返回代码,nginx 将其转换为 500,并且从服务器传递的响应正文包含在对客户端的响应中。我对 nginx 相当陌生,并且已经研究和尝试了几天,但没有运气。我认为这可以通过 proxy_set_header 或使用重写来完成。如果有人知道怎么做,请给个详细的例子。

【问题讨论】:

    标签: nginx


    【解决方案1】:

    您能否将响应正文作为字符串返回?

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

    【讨论】:

    • 这真是太棒了:)
    • 谢谢,圣弗朗西斯科!
    猜你喜欢
    • 2014-11-13
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多