http-enc-res-hdr.lua 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. -- 功能:编码 HTTP 返回头
  2. -- 阶段:header_filter_by_lua
  3. -- 备注:
  4. -- aceh = HTTP 返回头的 access-control-expose-headers 字段
  5. -- 无论浏览器是否支持,aceh 始终包含 *
  6. local expose = '*'
  7. -- 该值为 true 表示浏览器不支持 aceh: *,需返回详细的头部列表
  8. local detail = (ngx.ctx._aceh == 1)
  9. -- 由于接口路径固定,为避免被缓存,以请求头的 --url 值区分缓存
  10. local vary = '--url'
  11. local h, err = ngx.resp.get_headers()
  12. for k, v in pairs(h) do
  13. if
  14. -- 这些头有特殊意义,需要转义 --
  15. k == 'access-control-allow-origin' or
  16. k == 'access-control-expose-headers' or
  17. k == 'location' or
  18. k == 'set-cookie'
  19. then
  20. if type(v) == 'table' then
  21. for i = 1, #v do
  22. local x = i .. '-' .. k
  23. ngx.header[x] = v[i]
  24. if detail then
  25. expose = expose .. ',' .. x
  26. end
  27. end
  28. else
  29. local x = '--' .. k
  30. ngx.header[x] = v
  31. if detail then
  32. expose = expose .. ',' .. x
  33. end
  34. end
  35. ngx.header[k] = nil
  36. elseif k == 'vary' then
  37. if type(v) == 'table' then
  38. vary = vary .. ',' .. table.concat(v, ',')
  39. else
  40. vary = vary .. ',' .. v
  41. end
  42. elseif detail and
  43. -- 非简单头无法被 fetch 读取,需添加到 aceh 列表 --
  44. -- https://developer.mozilla.org/en-US/docs/Glossary/Simple_response_header
  45. k ~= 'cache-control' and
  46. k ~= 'content-language' and
  47. k ~= 'content-type' and
  48. k ~= 'expires' and
  49. k ~= 'last-modified' and
  50. k ~= 'pragma'
  51. then
  52. expose = expose .. ',' .. k
  53. end
  54. end
  55. if detail then
  56. expose = expose .. ',--s'
  57. ngx.header['--t'] = '1'
  58. end
  59. ngx.header['access-control-expose-headers'] = expose
  60. ngx.header['access-control-allow-origin'] = '*'
  61. ngx.header['vary'] = vary
  62. ngx.header['--s'] = ngx.status
  63. ngx.status = 200