NGINX/Gunicorn:返回JSON格式的错误消息

NGINX/Gunicorn:返回JSON格式的错误消息,nginx,http-headers,gunicorn,Nginx,Http Headers,Gunicorn,我使用NGINX作为gunicorn应用服务器的反向代理。当出现服务器错误(找不到url、请求超时等)时,响应将以html形式返回。我熟悉NGINX,我尝试在服务器块中放入一个错误指令,转发到我的应用服务器,如下所示,但是响应仍然以html形式返回。有什么想法吗 server { server_name rtj.foo.com; client_max_body_size 10M; location = /favicon.ico { access_

我使用NGINX作为gunicorn应用服务器的反向代理。当出现服务器错误(找不到url、请求超时等)时,响应将以html形式返回。我熟悉NGINX,我尝试在服务器块中放入一个错误指令,转发到我的应用服务器,如下所示,但是响应仍然以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;
        }

}

您需要通过添加和清空
types
块并将
default\u type
设置为
application/json
来覆盖请求文档的内容类型

有关详细信息,请参阅

例如:

error_page 404 /404.html;
location = /404.html {
    types {}
    default_type application/json;
    return 404 '{"error": {"status_code": 404,"status": "Not Found"}}';
}
如果URI不需要直接访问(即对
error\u页面
指令是私有的),则可以使用命名位置:

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

您需要通过添加和清空
types
块并将
default\u type
设置为
application/json
来覆盖请求文档的内容类型

有关详细信息,请参阅

例如:

error_page 404 /404.html;
location = /404.html {
    types {}
    default_type application/json;
    return 404 '{"error": {"status_code": 404,"status": "Not Found"}}';
}
如果URI不需要直接访问(即对
error\u页面
指令是私有的),则可以使用命名位置:

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

所以这对我不起作用。但是如果我做一些类似于
location=/test{*yourconfig*}
的事情,它就会工作。当请求到达服务器块时,它跳过
location=/404.html
,进入由我的应用服务器处理的
location/{}
。如果应用服务器找不到请求的资源…它要么用404响应,要么告诉nginx用404响应。我可能需要对此做更多的研究,因为我不确定哪个服务器正在响应。Gunicorn正在拦截错误。如果在上添加
proxy\u intercept\u错误在应用程序服务器的位置块中,它将起作用。因此,这对我不起作用。但是如果我做一些类似于
location=/test{*yourconfig*}
的事情,它就会工作。当请求到达服务器块时,它跳过
location=/404.html
,进入由我的应用服务器处理的
location/{}
。如果应用服务器找不到请求的资源…它要么用404响应,要么告诉nginx用404响应。我可能需要对此做更多的研究,因为我不确定哪个服务器正在响应。Gunicorn正在拦截错误。如果在上添加
proxy\u intercept\u错误在应用程序服务器的位置块中,它将工作。