nginxopenresty

How do I set default headers for upstream responses in nginx?


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:

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


Solution

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