Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come I cannot set multiple cookies

Tags:

openresty

I'm trying to set multiple cookies, but it's not working:

if type(ngx.header["Set-Cookie"]) ~= "table" then
    ngx.header["Set-Cookie"] = {}
end
table.insert(ngx.header["Set-Cookie"], "Cookie1=abc; Path=/")
table.insert(ngx.header["Set-Cookie"], "Cookie2=def; Path=/")
table.insert(ngx.header["Set-Cookie"], "Cookie3=ghi; Path=/")

On the client I do not receive any cookies.

like image 348
Dat Boi Avatar asked May 17 '17 06:05

Dat Boi


People also ask

Can you have multiple cookies?

Different browsers have different limitsMost browsers put a limit on the number of cookies any one domain can set. The minimum is set by the Request for Comments (RFC) standard established by the Internet Engineering Task Force, but browser makers can increase that number.

Can you have multiple set-cookie headers?

The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so that the user agent can send it back to the server later. To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.

Can I have 2 cookies with same name?

If multiple cookies of the same name match a given request URI, one is chosen by the browser. The more specific the path, the higher the precedence. However precedence based on other attributes, including the domain, is unspecified, and may vary between browsers.

How do you send multiple cookie requests?

To send a request with a Cookie, you need to add the "Cookie: name=value" header to your request. To send multiple cookies in a single Cookie header, separate them with semicolons or add multiple "Cookie: name=value" request headers.


1 Answers

ngx.header["Set-Cookie"] is a special table, and must be reassigned to with a new table every time you modify it (elements inserted or removed from it have no effect on the cookies that will be sent to the client):

if type(ngx.header["Set-Cookie"]) == "table" then
    ngx.header["Set-Cookie"] = { "AnotherCookieValue=abc; Path=/", unpack(ngx.header["Set-Cookie"]) }
else
    ngx.header["Set-Cookie"] = { "AnotherCookieValue=abc; Path=/", ngx.header["Set-Cookie"] }
end
like image 139
wilsonzlin Avatar answered Oct 10 '22 23:10

wilsonzlin