ngix.exit Terminate connection in access_by_lua

26 views
Skip to first unread message

Murali darvaja

unread,
Feb 7, 2017, 5:52:36 AM2/7/17
to openresty-en
Hi all,
I am writing a lua script for downloading a file with authentication. In access_by_lua_file I'm calling an API by using lua http resty and getting response, If the response status is 200 I have to allow for downloading the requested file, Otherwise I should terminate the connection. In header_filter_by_lua_file I'm setting all the headers for downloading a file.
nginx.conf
 location /download {
        access_by_lua_file
"/etc/nginx/luaFiles/auth.lua";
        header_filter_by_lua_file
"/etc/nginx/luaFiles/header.lua";
               
alias "/uploads/";
       
}

access_by_lua_file: auth.lua
In this file i'm calling an API, if status code return by api is not equal to 200 then I should terminate the connection without allowing the file to download. Here I'm using ngx.exit with the status code to terminate the connection. But
connection is not terminated it's still going in to the header_filter_by_lua_file.
if res then
   
if res.status==200 then
    ngx
.status=res.status
   
return
   
end
   
if res.status~=200 then
    ngx
.status=res.status
    ngx
.say("error code :",res.status)
   
return ngx.exit(res.status)
   
end
else
    ngx
.status=500
    ngx
.say("failed to request: ",err)
    ngx
.exit(500)
end

please help me to terminate the connection without going into header_filter_by_lua_file.

Robert Paprocki

unread,
Feb 7, 2017, 1:24:19 PM2/7/17
to openre...@googlegroups.com
Hi,


Basically, if you have a header_filter phase handler defined, it will almost always execute, because nginx still has to finalize the response resulting from ngx.exit(). You could work around this a bit by setting a flag in ngx.ctx to not execute code in header_filter based on certain conditions.
Reply all
Reply to author
Forward
0 new messages