Redirect to same url from Lua to Nginx (openresty setup)

I want to change the request header and redirect it to Lua, I have tried

 ngx.redirect("/")

      

and

 ngx.exec("/")

      

but I am getting the following error:

attempt to call ngx.redirect after sending out the headers

      

Is there an easy way to add a header value and redirect it somewhere else in Lua? I didn't find a suitable directive in the documentation, is there a way to do something like this when using content_by_lua_file ?

I am using openresty.

+3


source to share


1 answer


From the redirection documentation :

Note that this method call ends the processing of the current request and that it must be called before ngx.send_headers or explicit response body expressions via ngx.print or ngx.say.

So check it out or use another request phase handler like rewrite_by_lua .

As for setting the header, use ngx.header

eg:



location /testRedirect {
   content_by_lua '
     ngx.header["My-header"]= "foo"
     return ngx.redirect("http://www.google.com")
   ';
}

      

curl http://127.0.0.1/testRedirect

output:

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>

      

Note. Most sites DO NOT accept a custom header coming from a redirect, so consider using a cookie in this case.

+3


source







All Articles