Home > other >  NGINX Set header only if upstream responds with a custom header
NGINX Set header only if upstream responds with a custom header

Time:12-15

I have a upstream server that sets a Session-ID header only on some requests. I want to forward that session id in a cookie.

I tried something like this.

add_header   Set-Cookie "session_id=$sent_http_session_id;";

This works for request where the upstream server sets the header, but for requests where there is no header present, this results in the following HTTP header: Set-Cookie: session_id=;, which overwrites the correct cookie.

I tried with an if but that did not work:

if ($sent_http_session_id) {
    add_header   Set-Cookie "session_id=$sent_http_session_id";
}

How can I set an header only if the upstream responds with a custom header?

CodePudding user response:

After a lot of googling (we even looked on page 2 :P) we found a solution:

This works with a map, where $sent_http_session_id refers to the header that we want to map (see here):

map $sent_http_session_id $header_to_cookie {
    ""  "";                                     # No header results in no cookie
    default "session_id=$sent_http_session_id"; # Mapping from custom header to cookie
}

server{
    # ...
    
    location / {
        # ... 
        add_header                  Set-Cookie $header_to_cookie;
    }
}
  • Related