How to config nginx to only return the response from the proxy in case the content-type is correct?

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

In normal case, the proxy server will return image/png. But in other cases (for example out of bandwidth), it will throw application/json (with 200 HTTP) instead of images. So how to only accept images from the proxy, I want to show a 500 error page instead of it returning application/json from the proxy

1 Answers

An openresty/lua-ngx-module solution:

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
    }
}

or

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
    }
}
Related