How to replace *every* occurrence of a string in an NGINX response header with another value?

Viewed 1167

I have an Nginx setup that is using proxy_pass that talks to an internal server and returns the response. What I'd like to do - can I replace every instance of a specific string in a specific header with another word?

The proxy_pass points at an internal server, and in the response sends this header:

WWW-Authenticate: Bearer realm="https://someinternal.domain/v2/token",service="https://someinternal.domain/v2/token"

I'd like this to be overridden, replace the 'someinternal' strings with 'mypublic'

WWW-Authenticate: Bearer realm="https://mypublic.domain/v2/token",service="https://mypublic.domain/v2/token"

I'm aware of nginx's sub_filter, but that only seems to work on the body of the response, but not the headers.
I'm aware of proxy_redirect, but that only applies to the Location header.
So this question boils down to - how can I perform these URL replacements in custom headers?


I do have something working, but it feels inelegant; it'd be great if I could just replace all occurrences without knowing the structure of the header.

map $upstream_http_www_authenticate $newvalue {
  ~(.*)(someinternal)(.*)(someinternal)(.*)  $1mypublic$3mypublic$5;
  default "";
}

server {
    listen 80;

    location / {
      proxy_pass https://someinternal.domain/;
      proxy_hide_header 'WWW-Authenticate';
      add_header WWW-Authenticate $newvalue always;
    }
}

I'm using Nginx's map with regex to look for the 'someinternal' and then reconstructing the header with 'mypublic' in between the regex matches. I then use proxy_hide_header to hide the internal header, and add its replacement.

0 Answers
Related