WordPress “Error establishing a database connection” only when using nginx proxy

Solution:

I figured it out. The issue was

proxy_set_header Host $host;

The https://blog.example.com/ is a virtual host and nginx sends a request to it, as the request would be to https://example.com/blog, confusing the virtual hosts logic. The error itself is unrelated to the cause of the issue. There was a broken wordpress site on that (example.com/blog) url already.

The solution:

proxy_set_header Host blog.example.com; 

this would correctly get the correct site from virtual host, then the result is sent to the proxy server that would convert it to example.com/blog