如何在nginx中仅在content-type正确的情况下返回代理响应?

location / {
    proxy_pass       http://image_server:8000;
}

通常情况下,代理服务器将返回image/png。 但在其他情况下(例如超出带宽),它将抛出application/json(带有200 HTTP)而不是图片。 因此,如何仅从代理服务器接受图像? 我想显示一个500错误页面,而不是从代理返回application/json。

点赞
用户7121513
用户7121513

一个基于 openresty/lua-ngx-module 的解决方案:

location / {
    proxy_pass       http://image_server:8000;
    header_filter_by_lua_block {
        if string.find( ngx.header.content_type, "json" ) then
            ngx.exit(500)
        end
    }
}

或者

location / {
    proxy_pass       http://image_server:8000;
    header_filter_by_lua_block {
        if string.find( ngx.header.content_type, "image/" ) == nil then
            ngx.exit(500)
        end
    }
}
2020-06-08 19:49:57