title: How to replace *every* occurrence of a string in an NGINX response header with another value?
body: <p>I have an Nginx setup that is using <code>proxy_pass</code> 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?</p>
  
  <p>The <code>proxy_pass</code> points at an internal server, and in the response sends this header:</p>
  
  <pre><code>WWW-Authenticate: Bearer realm="https://someinternal.domain/v2/token",service="https://someinternal.domain/v2/token"
  </code></pre>
  
  <p>I'd like this to be overridden, replace the 'someinternal' strings with 'mypublic'</p>
  
  <pre><code>WWW-Authenticate: Bearer realm="https://mypublic.domain/v2/token",service="https://mypublic.domain/v2/token"
  </code></pre>
  
  <p>I'm aware of nginx's <code>sub_filter</code>, but that only seems to work on the body of the response, but not the headers.<br>
  I'm aware of <code>proxy_redirect</code>, but that only applies to the Location header.<br>
  So this question boils down to - how can I perform these URL replacements in custom headers? </p>
  
  <hr>
  
  <p>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. </p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>I'm using Nginx's <code>map</code> with regex to look for the 'someinternal' and then reconstructing the header with 'mypublic' in between the regex matches. I then use <code>proxy_hide_header</code> to hide the internal header, and add its replacement.  </p>