从重定向方法文档:
请注意,此方法调用会终止当前请求的处理,并且必须在 ngx.send_headers 或 ngx.print 或 ngx.say 的显式响应正文输出之前调用它。
因此,请检查或使用另一个请求阶段处理程序,例如rewrite_by_lua。
至于设置标题,请使用ngx.header
例如:
location /testRedirect {
content_by_lua '
ngx.header["My-header"]= "foo"
return ngx.redirect("http://www.google.com")
';
}
卷曲http://127.0.0.1/testRedirect
输出:
HTTP/1.1 302 Moved Temporarily
Server: openresty
Date: Tue, 30 Jun 2015 17:34:38 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
My-header: foo
Location: http://www.google.com
<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>
注意:大多数网站不会接受来自重定向的自定义标头,因此请考虑在这种情况下使用 cookie。