Redirect to same URL with Lua on Nginx (openresty setup)

anshulv picture anshulv · Jun 30, 2015 · Viewed 7.9k times · Source

I'm looking to modify a request header and redirect it in Lua, I've tried

 ngx.redirect("/")

and

 ngx.exec("/")

but I'm getting following error:

attempt to call ngx.redirect after sending out the headers

Is there a straightforward way to add a header value and redirect it somewhere else in Lua? In the documentation I didn't find any appropriate directive, Is there a way something like this can be done while still using content_by_lua_file ?

I'm using openresty.

Answer

danielgpm picture danielgpm · Jun 30, 2015

From the redirect method documentation:

Note that this method call terminates the processing of the current request and that it must be called before ngx.send_headers or explicit response body outputs by either ngx.print or ngx.say.

So check that or use another request phase handler such as rewrite_by_lua.

As for setting a header, use ngx.header

E.g:

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 will NOT accept custom header coming from a redirect, so consider using a cookie on that case.