Welcome! Log In Create A New Profile

Advanced

Re: Response headers adding/filtering during proxy with njs

Dmitry Volyntsev
January 19, 2021 02:54PM
On 19.01.2021 18:44, Grzegorz Kulewski wrote:
> Hello,
>
> Is it possible to (at least) add (or better also) filter response headers (like for example setting or modifying or deleting cookies, of course without harming other cookies set by the upstream) dynamically from njs after it is returned from the upstream (or cache) and before it is sent to the client?
>
> I think something like that is possible with lua but I would really like to avoid using 3rd party modules and just go the njs route.
>
> If not possible - is there any workaround? And/or can it be easily added in next release(s)?
>
> Thank you in advance.
>

Hi Grzegorz,

Please, clarify what are you trying to do with Set-Cookie headers?
Consider built-in directives for a typical modifications like
proxy_cookie_domain, proxy_cookie_flags etc.

If nothing is applicable take a look at the following example:

nginx.conf:

js_import main from http.js;
js_set $modify_cookies  main.modify_cookies;

location /modify_cookies {
            add_header _ $modify_cookies;
            proxy_pass http://127.0.0.1:8080;
 }

server {
        listen       127.0.0.1:8080;

        location /modify_cookies {
            add_header Set-Cookie "XXXXXX";
            add_header Set-Cookie "BB";
            add_header Set-Cookie "YYYYYYY";
            return 200;
        }
    }

http.js:
function modify_cookies(r) {
    var cookies = r.headersOut['Set-Cookie'];
    r.headersOut['Set-Cookie'] = cookies.filter(v=>v.length >
Number(r.args.len));
    return "";
}


curl http://localhost:8000/modify_cookies?len=1 -v
...
< Set-Cookie: XXXXXX
< Set-Cookie: BB
< Set-Cookie: YYYYYYY



curl http://localhost:8000/modify_cookies?len=3 -v
...
< Set-Cookie: XXXXXX
< Set-Cookie: YYYYYYY


This works because arbitrary njs code can be executed when nginx
evaluates a variable at runtime.
The trick is to find an appropriate directives which supports variables
and which is evaluated at appropriate moment of request processing. So,
in the example an auxiliary variable is used to inject njs code after an
upstream data is processed but response headers are not sent to a client
yet.



_______________________________________________
nginx mailing list
nginx@nginx.org
http://mailman.nginx.org/mailman/listinfo/nginx
Subject Author Posted

Response headers adding/filtering during proxy with njs

Grzegorz Kulewski January 19, 2021 10:46AM

Re: Response headers adding/filtering during proxy with njs

Dmitry Volyntsev January 19, 2021 02:54PM



Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 219
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready