If we want to return specific status codes from our
Lua code we should have the following in mind:
ngx.say("hello") return ngx.exit(404)
200 response code
ngx.status = 404 ngx.say("hello") return ngx.exit(404)
404 response code
BTW that last line
return ngx.exit(404)is there to reinforce the code and exist the request.
There is no better way to explain what's happening than read Yichun Zhang comments about the matters:
By default, ngx_lua output response data in a non-buffered manner (in order to save memory and increase I/O and CPU overlapping). When you call ngx.say() for the first time, the response header will automatically be sent right away if it is not sent yet. After that, even if you call ngx.exit(404), the response header cannot be altered because it has already been sent out (unless you have a time machine).