1

I want to make sure that at least the default header value is always returned from upstream. Even if upstream is unavailable, which causes error 5xx.

Now I have tried these nginx config options:

server {
  ...
  #add_header "Access-Control-Allow-Origin" "*"; №0
  #add_header "Access-Control-Allow-Origin" "*" always; №1
  #more_set_headers "Access-Control-Allow-Origin: *"; №2
  #more_set_headers -s '403 500 502 504 503' "Access-Control-Allow-Origin: *"; №3

  location /upstream {
    proxy_pass http://localhost:1234;
  }
  ...
}

There are problems with all the options:

  • №0: Duplicates the header, and in the case of 5xx will not return any.
  • №1: Duplicates the header
  • №2: Overrides the upstream header
  • №3: If the upstream ended with a good http code, but did not return a header, it will not add a header.

I think I'm close to the right solution, but I can't find it.

deevroman
  • 99
  • 1
  • 2
  • 14

1 Answers1

2

The map below uses a regex, /.+/, to check if the Access-Control-Allow-Origin header is defined. If so, it assigns its value to the $acao custom variable. Otherwise, it assigns the default value * to $acao;

To avoid duplications, use proxy_hide_header

Finally, add the header using the $acao variable content.

http {
  map $upstream_http_access_control_allow_origin $acao {
    ~.+ $upstream_http_access_control_allow_origin;
    default '*';
  }

  server {
    #…
    proxy_hide_header Access-Control-Allow-Origin;
    add_header Access-Control-Allow-Origin $acao always;
  
    location /upstream {
      proxy_pass http://localhost:1234;
    }
}
Eric Fortis
  • 16,372
  • 6
  • 41
  • 62
  • 1
    It seems that this is almost what is needed. The only thing is, you still need to add `always` or use `more_set_headers` so that the headers are shown in case of errors. – deevroman Feb 20 '23 at 07:56