【PL/SQL Developer连接MS SQL Ser
975 2023-04-02 17:06:25
在or中简单的使用cookies 复杂的操作请使用
[lua_resty_cookies]
(https://github.com/cloudflare/lua-resty-cookie)
local cookie_name = "cookie_session"ngx.say(ngx.var[cookie_name])
ngx.header["Set-Cookie"] = "session=af54; Path=/; Expires=" .. ngx.cookie_time(ngx.time() + 86400)
测试代码
location ~ /header_add { content_by_lua_block { ngx.header["Set-Cookie"] = "session=lzz; Path=/; Expires=" .. ngx.cookie_time(ngx.time() + 86400) ngx.say("orangleliu") } }
看看效果
# curl -i 127.0.0.1:8001/header_addHTTP/1.1 200 OKServer: openresty/1.9.7.1Date: Fri, 16 Dec 2016 07:00:30 GMTContent-Type: text/htmlTransfer-Encoding: chunkedConnection: keep-aliveSet-Cookie: session=lzz; Path=/; Expires=Sat, 17-Dec-16 07:00:30 GMT
function get_cookies() local cookies = ngx.header["Set-Cookie"] or {} if type(cookies) == "string" then cookies = {cookies} end return cookiesendfunction add_cookie(cookie) local cookies = get_cookies() table.insert(cookies, cookie) ngx.header['Set-Cookie'] = cookiesendadd_cookie("session=aff12d; Path=/")
⚠️:上面的代码需要在 header_filter
阶段运行,在这个阶段可以获取 应用或者是后端 proxy 设置的cookies, 如果你想要 添加,删除,替换某一个cookies,注意不要覆盖所有的 cookies了。
一个例子,在content阶段设置了多个cookies,然后在 header_filter
阶段删除cookies
location ~ /header_delete { content_by_lua_block { ngx.header["Set-Cookie"] = {'Foo=abc; path=/', 'age=18; path=/'} ngx.say("openresty") } header_filter_by_lua_block { local match = string.match local function get_cookies() -- local cookies = ngx.header["Set-Cookie"] or {} local cookies = ngx.header.set_cookie or {} if type(cookies) == "string" then cookies = {cookies} end return cookies end local function remove_cookie(cookie_name) local cookies = get_cookies() ngx.log(ngx.ERR, "source cookies ", table.concat(cookies, " ")) for key, value in ipairs(cookies) do local name = match(value, "(.-)=") ngx.log(ngx.ERR, key.."<=>", value) if name == cookie_name then table.remove(cookies, key) end end ngx.header['Set-Cookie'] = cookies or {} ngx.log(ngx.ERR, "new cookies ", table.concat(cookies, " ")) end remove_cookie("Foo") } }}
测试下
# curl '127.0.0.1:8001/header_delete' -iHTTP/1.1 200 OKServer: openresty/1.9.7.1Date: Fri, 16 Dec 2016 08:07:34 GMTContent-Type: text/htmlTransfer-Encoding: chunkedConnection: keep-aliveSet-Cookie: age=18; path=/
使用 header_filter_by_lua
指令
header_filter_by_lua ' local cookies = ngx.header.set_cookie if cookies then if type(cookies) ~= "table" then cookies = {cookies} end local gsub = string.gsub local changed for i, cookie in ipairs(cookies) do local new_cookie = gsub(cookie, "^target%-cookie=[^;]*", "target-cookie=myvalue", 1) if new_cookie ~= cookie then cookies[i] = new_cookie changed = true end end if changed then ngx.header.set_cookie = cookies end end';
https://github.com/openresty/headers-more-nginx-module/issues/18
header_filter_by_lua add cookies
邮件列表ngx_http_headers_module