FIX: missing CORS headers on error response [nginx]
The title of this post is my commit message. It’s a short one, but I believe crucial to share, as I just spent roughly speaking 4 hours attempting to debug this issue, and with any further attempt I failed even worse.
Long story short, I attempted to modify response headers of my reverse proxy server. It appeared to be just fine initially — a successful (200) response, with a full set of headers, but the reality hit me pretty quickly, after seeing a bunch of CORS errors on 401’s. The headers were just there, in the config file — I tried moving the headers around the file, thinking maybe a different set of rules applies to
proxy_pass. Didn’t work. No mention of it on stackoverflow, github, ducking didn’t help either. I looked everywhere, but not the documentation — who tf even reads it, right? Here’s what it says about the
Adds the specified field to a response header provided that the response code equals 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0). Parameter value can contain variables.
Right. No mention of 40X or 50X responses. Why? Only god knows. But there's a trick. All you gotta do is to add the
always tag at the end of the directive, and the header will appear on ANY response, regardless of its response code.
add_header ‘Access-Control-Allow-Origin’ example.com always;