【问题标题】:NGINX / Gunicorn: Return JSON formatted Error MessagesNGINX / Gunicorn:返回 JSON 格式的错误消息
【发布时间】:2020-06-12 04:02:10
【问题描述】:

我使用 NGINX 作为 gunicorn 应用服务器的反向代理。当出现服务器错误(未找到 url、请求超时等)时,响应将作为 html 返回。我熟悉 NGINX 的 error page directive 并且我尝试在服务器块中放置一个错误指令,该指令转发到我的应用程序服务器,如下所示,但响应仍以 html 形式返回。有什么想法吗?

server {
        server_name rtj.foo.com;
        client_max_body_size 10M;

        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
            root /home/ubuntu/api;
        }

        error_page 404 /404.html;
        location /404.html{
            return 404 '{"error": {"status_code": 404,"status": "Not Found"}}';
        }

        location / {
            include proxy_params;
            proxy_pass http://unix:/run/gunicorn.sock;
        }

}

【问题讨论】:

    标签: nginx http-headers gunicorn


    【解决方案1】:

    您需要通过添加并清空types 块并将default_type 设置为application/json 来覆盖所请求文档的内容类型。

    详情请见this document

    例如:

    error_page 404 /404.html;
    location = /404.html {
        types {}
        default_type application/json;
        return 404 '{"error": {"status_code": 404,"status": "Not Found"}}';
    }
    

    如果 URI 不需要直接访问(即对 error_page 指令是私有的),您可以使用命名位置:

    error_page 404 @error404;
    location @error404 {
        types {}
        default_type application/json;
        return 404 '{"error": {"status_code": 404,"status": "Not Found"}}';
    }
    

    【讨论】:

    • 所以这对我不起作用。但是,如果我执行location = /test { *your config* } 之类的操作,它就会起作用。当请求到达服务器块时,它会跳过location = /404.html 并转到由我的应用程序服务器处理的location / {}。如果应用程序服务器没有找到请求的资源......它要么响应 404,要么告诉 nginx 响应 404。我可能需要对此进行更多研究,因为我不确定哪个服务器在响应。跨度>
    • Gunicorn 正在拦截错误。如果您在应用程序服务器的位置块中添加proxy_intercept_errors on;,它将起作用。
    猜你喜欢
    • 2016-10-06
    • 1970-01-01
    • 2015-08-31
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 2020-01-23
    相关资源
    最近更新 更多