When the response header is too large, nginx will reject it and return 502 Bad Gateway, this is because the default proxy buffer size is not large enough.
If you inspect the error.log file under /var/nginx, you will find this error
upstream sent too big header while reading response header from upstream
Change the following settings under location to fix this issue by making the buffers larger
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
After fixing this, if you encounter error: Request header or cookie too long. You can fix it by setting the buffer size for client header under server configuration context.
large_client_header_buffers 4 24k