proc-redir.lua 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. -- https://fetch.spec.whatwg.org/#statuses
  2. local s = ngx.status
  3. if not (s == 301 or s == 302 or s == 307 or s == 308) then
  4. return
  5. end
  6. -- 忽略 WebSocket
  7. if ngx.header['upgrade'] then
  8. return
  9. end
  10. --[=[
  11. 如果直接返回 30X 状态,fetch API 会继续请求新的 URL,
  12. 不符合 req.redirect 为 manual 的情况。
  13. 例如请求 google.com 会重定向到 www.google.com,
  14. 如果最终获得的内容是后者,但地址栏显示的是前者,路径上就会出现问题。
  15. 如果在 SW 里设置 req.redirect = manual,重定向后拿不到 location。
  16. 所以这里对状态码 + 10 进行转义,SW 收到后再 -10。
  17. ]=]
  18. ngx.status = s + 10
  19. ngx.header['access-control-expose-headers'] = 'location'
  20. -- local url = ngx.header['location']
  21. -- if not url then
  22. -- return
  23. -- end
  24. -- -- m = [, rhost, path]
  25. -- local r = [[^https?://([^/]+)(.*)]]
  26. -- local m = ngx.re.match(url, r, 'jo')
  27. -- if not m then
  28. -- return
  29. -- end
  30. -- -- rhost to vhost
  31. -- ngx.var._rhost = m[1]
  32. -- local vhost = ngx.var._rhost_to_vhost
  33. -- url = 'https://' .. vhost .. m[2]
  34. -- -- add flag
  35. -- local sign = url:find('?', 1, true) and '&' or '?'
  36. -- url = url .. sign .. 'flag__=' .. ngx.var._flag
  37. -- -- update redir url
  38. -- ngx.header['location'] = url