nginxhttp-redirectheadernjs

Redirect with Location header using njs subrequest


I need send some request to the app before using it and redirect browser to location from reply of that request in case of status = 302.

nginx.conf:

http {
  upstream app {
    server localhost:3000;
  }
  server {
    server_name myhost.local;
    js_import 'lib.js';
    location / {
      js_content lib.check;
    }
    location = /app {
      internal;
      proxy_pass http://app$request_uri;
    }
  }
}

lib.js:

async function check(r) {
 let reply = await r.subrequest('/app')
 if (reply.status == 302) {
   r.headersOut['Location'] = reply.headersOut['Location']<--doesn't work
   r.headersOut['Foo'] = 'Bar'<--works       
 }
 r.headersOut['Content-Type'] = reply.headersOut['Content-Type']<--also works  
 r.return(reply.status, reply.responseText) 
}

The problem is Location header is Host value:

curl -I myhost.local 
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.26.2
Location: http://myhost.local/ <--Host
Foo: Bar <--ok
Content-Type: text/html <--ok

The reply.headersOut has Location with proper value, Foo and Content-Type headers work as expected, but not Location one. How to deal with it?


Solution

  • I found the solution here.
    The second argument in r.return can be a redirect URL for 302 code:

     if (reply.status == 302) {
       r.return(reply.status, reply.headersOut['Location'])
       return
     }
     r.return(reply.status, reply.responseText)