Nginx Lua set-cookie header overwriting / removing any other set-cookie responses that may be present

3,823 views
Skip to first unread message

c0nw...@googlemail.com

unread,
Sep 9, 2016, 10:31:04 AM9/9/16
to openresty-en
So the following keeps overwriting / removing any other set-cookie responses that may be present in the response.


if ($host ~* www(.*)) {
 
set $host_without_www $1;
}
header_filter_by_lua
'
 ngx.header["Set-Cookie"] = "value=1; path=/; domain=" .. ngx.var.host_without_www .. "; expires=" .. ngx.cookie_time(ngx.time()+2592000) .. "; Max-Age=2592000" -- +1 month 30 days
'
;



What is the correct way to stop lua from what seems to be intentional removing all the other set-cookie responses rather than just adding this to them.


The way it should be working is to leave all other set-cookie headers there and just add that as another cookie in the response.

Robert Paprocki

unread,
Sep 9, 2016, 12:11:03 PM9/9/16
to openre...@googlegroups.com
Since cookies are generally more complex than other headers, you may want to check out the lua-resty-cookie library, which is designed to handle and manipulate request and response cookies.

Well the long answer is that multiple header values are treated as a lua table, so you would need to extra the existing set-cookie header from the upstream response, push your new cookie value on to the table, and reset the header with that table. But this is more complex. 
--
You received this message because you are subscribed to the Google Groups "openresty-en" group.
To unsubscribe from this group and stop receiving emails from it, send an email to openresty-en...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

c0nw...@googlemail.com

unread,
Sep 10, 2016, 7:52:33 AM9/10/16
to openresty-en
To save over complicating what could be a easy task isit possible for me to put this LUA value into something nginx can use.

Lua value
ngx.time()+2592000

To be used inside this
if ($host ~* www(.*)) {
 
set $host_without_www $1;
}

add_header
Set-Cookie "value=1;domain=$host_without_www;path=/;expires="LUA VALUE HERE";Max-Age=2592000";

The way add_header works is the way i would like it to function i just need that ngx.time output to set the expires time of my cookie due to the fact old browsers IE8 lower etc don't know how to use the Max-Age so they expire the cookie at end of session but all browsers old and modern understand expires inside of cookies so for compatibility sakes its why i want to use it.

c0nw...@googlemail.com

unread,
Sep 10, 2016, 8:41:32 AM9/10/16
to openresty-en
I just figured it out a much easyer and more simple way my full code is now this

if ($host ~* www(.*)) {
 
set $host_without_www $1;
}
set_by_lua $expires_time 'return ngx.cookie_time(ngx.time()+2592000)';
add_header
Set-Cookie "value=1;domain=$host_without_www;path=/;expires=$expires_time;Max-Age=2592000";

:)
Reply all
Reply to author
Forward
0 new messages