Interpretation of nginx lua api

  nginx

Order

This article mainly explains the main methods and api of nginx lua module.

Ngx_lua operation phase

initialization phase

  • init_by_lua

Used in http module, commonly used in application of global variables

  • init_worker_by_lua

The specified lua code is called when each nginx worker process starts.

rewrite / access phase

  • set_by_lua:

Set a variable and calculate the variable for subsequent use.

  • rewrite_by_lua

It can be used instead of the rewrite instruction of HttpRewriteModule and has lower priority than the rewrite instruction.

  • access_by_lua

Can be used to modify request parameters

content phase

  • content_by_lua

The ngx returns the content without going to the proxied backend.

  • header_filter_by_lua

Can be used to modify the header of the backend response

  • body_filter_by_lua

It is usually called multiple times in a request because it implements the so-called “streaming output” based on HTTP 1.1 chunked encoding.

log phase

  • log_by_lua

Run at the end of the request, can do some statistical work

nginx api for lua

ngx.cookie_time

Ngx. Cookie _ time (ngx.time ()+60 * 30)-set cookie expiration time to 30 minutes

ngx.ctx

The context of the current request

ngx.decode_args

Decode is table.

local decoded_uri=ngx.decode_args("arg1=day1&arg2= monday");
print_t(decoded_uri);
function print_t(t)
    for k, v in pairs(t) do
        if type(v) == table then
            ngx.say(k, ": ", table.concat(v), "<br/>");
        else
            ngx.say(k, ": ", v, "<br/>");
        end
    end
end

ngx.encode_args

Encode table into form submission format, a1=arg1&a2=arg2

ngx.say("encode args ", ngx.encode_args({a1="arg1", a2="arg2"}), "<br/>");

ngx.eof

Identifies the end of the response, ngx.eof () just ends the output of the response flow, interrupts the HTTP connection, and the following code logic will continue to execute on the server side.

ngx.req.read_body()
local uri_args = ngx.req.get_uri_args(1)
ngx.say(cjson.encode{result="refuse"})
ngx.eof()

ngx.escape_uri

Uri encoding

local fileName = "专辑列表.csv"
ngx.header.content_type = "text/csv;charset=utf-8"
ngx.header["Content-disposition"] = "attachment;filename=" .. ngx.escape_uri(fileName)

ngx.exec

Internal redirection

location /foo {
    content_by_lua '
        return ngx.exec('/some-location', 'a=3&b=5&c=6');
    ';
}

ngx.exit

When the incoming status >= 200(200 is ngx.HTTP_OK), ngx.exit () interrupts the current request and returns the incoming status code (status) to nginx.

When the incoming status == 0(0 is ngx.OK), ngx.exit () will interrupt the currently executing phrase (the phase when the NGX-LUA module processes the request, such as content_by_lua*), and then continue to execute the following PHRASE.

For ngx.exit (), further attention should be paid to the use of the parameter status. status can pass in all HTTP status code constants defined by ngx-lua (e.g., ngx.HTTP_OK, ngx.HTTP_GONE, ngx.HTTP_INTERNAL_SERVER_ERROR, etc.) and two ngx-lua module kernel constants (only NGX_OK and NGX_ERROR are supported. If other parameters such as ngx.AGAIN are passed in, the process hang lives).

The ngx.exit () best practice recommended in the document is used in combination with the return statement to enhance the semantics of the request being terminated (RETURNGX. exit (…).

if not ngx.var.arg_token then
        ngx.log(ngx.ERR, "Unauthorized")
        return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end

Cooperate with return to enhance exit semantics and prevent errors.

ngx.flush

ngx.say("Hello, Lua!")
ngx.flush(true)

If set to true, the contents of ngx.print or ngx.say will not be returned until they are written to send buffer.

ngx.get_phase

Returns the current processing stage, init, init_worker,
ssl_cert, set, rewrite, balancer, access, content, header_filter, body_filter, log, or
Timer one of these

ngx.http_time

ngx.header['Content-Type']  = 'application/json; charset=utf-8';
ngx.header['Expires']       = ngx.http_time( ngx.time() + max_age );
ngx.say(ngx.http_time(1290079655))
-- yields "Thu, 18 Nov 2010 11:27:35 GMT"

ngx.is_subrequest

Returns true if it is a subrequest.

ngx.localtime

Time to return yyy-mm-ddhh: mm: ss format from NGINX’s cache

ngx.location.capture

For sub-requests, return: status, header, body, and truncated.

ngx.log

The first parameter is log basic (one of NGX.stderr, NGX.emerg, NGX.alert, NGX.crit, NGX.err, NGX.warn, NGX.notice, NGX.info, and NGX.debug)
Log can be printed after receiving multiple parameters.

ngx.now

The number of milliseconds since the epoch time was returned from NGINX’s cache.
Ngx.now () is erroneous because nginx’s own time cache is used. For timing with high precision requirements, the following call sequence should be used:

ngx.update_time()
local now = ngx.now()

It is worth mentioning that ngx.now () has only millisecond precision.

ngx.parse_http_time

 local time = ngx.parse_http_time("Thu, 18 Nov 2010 11:27:35 GMT")
 if time == nil then
     ...
 end

ngx.print

Print to response body.

ngx.say

Print to response body and wrap

ngx.status

Http status status code

ngx.time

The number of seconds since nginx cached returned to epoch time.

ngx.today

Returns the current date from NGINX’s cache in the format yyyy-mm-dd

ngx.unescape_uri

ngx.say(ngx.unescape_uri("b%20r56+7"))
-- 返回b r56 7

ngx.update_time

Update NGINX’s time cache

ngx.utctime

Return utcttime from NGINX’s cache in format yyyy-mm-dd hh:mm:ss

doc