Home Backend Development PHP Tutorial ngx_lua module API description

ngx_lua module API description

Jul 30, 2016 pm 01:31 PM
http location lua

ANGX_LUA module API description

#ngx instructions Lua_Code_cache on | off;



Activity: Open or close the lua code cache, affect the following instructions: set_by_Lua_file, Content_BY_LUA_FILE, REWRITE_BY_LUA_FILE, Access_by_LUA_FILE and forced loading or RELOAD LUA module, cache, etc. Modifying the LUA code requires restarting nginx when it is enabled, but not when it is not enabled. Caching is generally turned off during the development phase.
Scope: main, server, location, location iflua_regex_cache_max_entries 1024;

Function: Unknown (seems to limit the maximum number of cached regular expression processing results)lua_package_path.../path... ;

Function: Set the extension library path written in lua code.
Example: lua_package_path '/foo/bar/?.lua;/blah/?.lua;;';lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;';

Function: Set the lua library path of the C extension. set_by_lua $var '' [$arg1 $arg2];set_by_lua_file $var [$arg1 $arg2 ...];


Function: Set an Nginx variable, and the variable value is calculated from the Lua script and returned by return, which can implement complex assignment logic; this is blocking, and the Lua code must be very fast.
In addition, the existing ngx variable can be used as The parameters are passed into the Lua script and accessed through ngx.arg[1], ngx.arg[2], etc.
Scope: main, server, location, server if, location if
Processing stage: rewritecontent_by_lua '';content_by_lua_file luafile;


Scope: location, location if
Description: Content processor, receives request processing and outputs response. content_by_lua directly writes shorter Lua code in nginx configuration file. The latter uses lua file. rewrite_by_lua ''rewrite_by_lua_file lua_file;


Scope: http, server, location, location if
Perform internal URL rewriting or external redirection, typical such as pseudo-static URL rewriting . Its default execution is at the end of the rewrite processing phase.
Note that when using rewrite_by_lua, you cannot see the corresponding rewrite log after turning on rewrite_log on;. access_by_lua 'lua code';access_by_lua_file lua_file.lua;


Function: used for access control. For example, we only allow intranet IP access, you can use the following form.
access_by_lua '
if ngx.req.get_uri_args()["token"] ~= "123" then
return ngx.exit(403)
end ';
Scope :http, server, location, location ifheader_filter_by_lua 'lua code';header_filter_by_lua_file path_file.lua;


Function: Set header and cookie;lua_need_request_body on|off;

Function: Whether to read the request body, follow ngx The .req.read_body() function works similarly, but this method is not officially recommended. lua_shared_dict shared_data 10m;

Function: Set up a shared global variable table to be shared among all worker processes. It can be accessed in the lua script as follows:
Example: local shared_data = ngx.shared.shared_data
10m I don’t know what it means. init_by_lua 'lua code'; init_by_lua_file lua_file.lua;


Scope: http
Description: Executed when the ginx Master process loads the configuration; usually used to initialize global configuration/preload Lua modules init_worker_by_lua 'lua code' ;init_worker_by_lua_file luafile.lua;


Scope: http

Description: A timer called when each Nginx Worker process starts. If the Master process is not allowed, it will only be called after init_by_lua; usually used for timing pulls Get configuration/data, or health check of backend service. ####################

Methods and constants ################# ####

ngx.arg[index]  			#ngx指令参数,当这个变量在set_by_lua或者set_by_lua_file内使用的时候是只读的,指的是在配置指令输入的参数.
ngx.var.varname  			#读写NGINX变量的值,最好在lua脚本里缓存变量值,避免在当前请求的生命周期内内存的泄漏
ngx.config.ngx_lua_version 	#当前ngx_lua模块版本号
ngx.config.nginx_version 	#nginx版本
ngx.worker.exiting 			#当前worker进程是否正在关闭
ngx.worker.pid				#当前worker进程的PID
ngx.config.nginx_configure	#编译时的./configure命令选项
ngx.config.prefix 			#编译时的prefix选项

core constans:				#ngx_lua 核心常量
	ngx.OK (0)
	ngx.ERROR (-1)
	ngx.AGAIN (-2)
	ngx.DONE (-4)
	ngx.DECLINED (-5)
	ngx.nil
http method constans:		#经常在ngx.location.catpure和ngx.location.capture_multi方法中被调用.
	ngx.HTTP_GET
	ngx.HTTP_HEAD
	ngx.HTTP_PUT
	ngx.HTTP_POST
	ngx.HTTP_DELETE
	ngx.HTTP_OPTIONS  
	ngx.HTTP_MKCOL    
	ngx.HTTP_COPY      
	ngx.HTTP_MOVE     
	ngx.HTTP_PROPFIND 
	ngx.HTTP_PROPPATCH 
	ngx.HTTP_LOCK 
	ngx.HTTP_UNLOCK    
	ngx.HTTP_PATCH   
	ngx.HTTP_TRACE  
http status constans: 		#http请求状态常量 
	ngx.HTTP_OK (200)
	ngx.HTTP_CREATED (201)
	ngx.HTTP_SPECIAL_RESPONSE (300)
	ngx.HTTP_MOVED_PERMANENTLY (301)
	ngx.HTTP_MOVED_TEMPORARILY (302)
	ngx.HTTP_SEE_OTHER (303)
	ngx.HTTP_NOT_MODIFIED (304)
	ngx.HTTP_BAD_REQUEST (400)
	ngx.HTTP_UNAUTHORIZED (401)
	ngx.HTTP_FORBIDDEN (403)
	ngx.HTTP_NOT_FOUND (404)
	ngx.HTTP_NOT_ALLOWED (405)
	ngx.HTTP_GONE (410)
	ngx.HTTP_INTERNAL_SERVER_ERROR (500)
	ngx.HTTP_METHOD_NOT_IMPLEMENTED (501)
	ngx.HTTP_SERVICE_UNAVAILABLE (503)
	ngx.HTTP_GATEWAY_TIMEOUT (504) 

Nginx log level constants:		#错误日志级别常量 ,这些参数经常在ngx.log方法中被使用.
	ngx.STDERR
	ngx.EMERG
	ngx.ALERT
	ngx.CRIT
	ngx.ERR
	ngx.WARN
	ngx.NOTICE
	ngx.INFO
	ngx.DEBUG

##################
#API中的方法:
##################
print()							#与 ngx.print()方法有区别,print() 相当于ngx.log()
ngx.ctx 						#这是一个lua的table,用于保存ngx上下文的变量,在整个请求的生命周期内都有效,详细参考官方
ngx.location.capture() 			#发出一个子请求,详细用法参考官方文档。
ngx.location.capture_multi() 	#发出多个子请求,详细用法参考官方文档。
ngx.status 						#读或者写当前请求的相应状态. 必须在输出相应头之前被调用.
ngx.header.HEADER 				#访问或设置http header头信息,详细参考官方文档。
ngx.req.set_uri() 				#设置当前请求的URI,详细参考官方文档
ngx.set_uri_args(args) 			#根据args参数重新定义当前请求的URI参数.
ngx.req.get_uri_args()			#返回一个LUA TABLE,包含当前请求的全部的URL参数
ngx.req.get_post_args()			#返回一个LUA TABLE,包括所有当前请求的POST参数
ngx.req.get_headers()			#返回一个包含当前请求头信息的lua table.
ngx.req.set_header()			#设置当前请求头header某字段值.当前请求的子请求不会受到影响.
ngx.req.read_body()				#在不阻塞ngnix其他事件的情况下同步读取客户端的body信息.[详细]
ngx.req.discard_body()			#明确丢弃客户端请求的body
ngx.req.get_body_data()			#以字符串的形式获得客户端的请求body内容
ngx.req.get_body_file()   	 	#当发送文件请求的时候,获得文件的名字
ngx.req.set_body_data()			#设置客户端请求的BODY
ngx.req.set_body_file()			#通过filename来指定当前请求的file data。
ngx.req.clear_header()			#清求某个请求头
ngx.exec(uri,args)				#执行内部跳转,根据uri和请求参数
ngx.redirect(uri, status)		#执行301或者302的重定向。
ngx.send_headers()				#发送指定的响应头
ngx.headers_sent 				#判断头部是否发送给客户端ngx.headers_sent=true
ngx.print(str)					#发送给客户端的响应页面
ngx.say()						#作用类似ngx.print,不过say方法输出后会换行
ngx.log(log.level,...)			#写入nginx日志
ngx.flush()						#将缓冲区内容输出到页面(刷新响应)
ngx.exit(http-status)			#结束请求并输出状态码
ngx.eof()						#明确指定关闭结束输出流
ngx.escape_uri()				#URI编码(本函数对逗号,不编码,而php的urlencode会编码)
ngx.unescape_uri()				#uri解码
ngx.encode_args(table)			#将tabel解析成url参数
ngx.decode_args(uri)			#将参数字符串编码为一个table
ngx.encode_base64(str)			#BASE64编码
ngx.decode_base64(str)			#BASE64解码
ngx.crc32_short(str)			#字符串的crs32_short哈希
ngx.crc32_long(str)				#字符串的crs32_long哈希
ngx.hmac_sha1(str)				#字符串的hmac_sha1哈希
ngx.md5(str)					#返回16进制MD5
ngx.md5_bin(str)				#返回2进制MD5
ngx.today()						#返回当前日期yyyy-mm-dd
ngx.time()						#返回当前时间戳
ngx.now()						#返回当前时间
ngx.update_time()				#刷新后返回
ngx.localtime()					#返回 yyyy-mm-dd hh:ii:ss
ngx.utctime()					#返回yyyy-mm-dd hh:ii:ss格式的utc时间
ngx.cookie_time(sec)			#返回用于COOKIE使用的时间
ngx.http_time(sec)				#返回可用于http header使用的时间		
ngx.parse_http_time(str)		#解析HTTP头的时间
ngx.is_subrequest 				#是否子请求(值为 true or false)
ngx.re.match(subject,regex,options,ctx)  	#ngx正则表达式匹配,详细参考官网
ngx.re.gmatch(subject,regex,opt)			#全局正则匹配
ngx.re.sub(sub,reg,opt)			#匹配和替换(未知)
ngx.re.gsub()					#未知
ngx.shared.DICT 				#ngx.shared.DICT是一个table 里面存储了所有的全局内存共享变量
	ngx.shared.DICT.get	 
	ngx.shared.DICT.get_stale	 
	ngx.shared.DICT.set	 
	ngx.shared.DICT.safe_set	 
	ngx.shared.DICT.add	 
	ngx.shared.DICT.safe_add	 
	ngx.shared.DICT.replace	 
	ngx.shared.DICT.delete	 
	ngx.shared.DICT.incr	 
	ngx.shared.DICT.flush_all	 
	ngx.shared.DICT.flush_expired	 
	ngx.shared.DICT.get_keys
ndk.set_var.DIRECTIVE			#不懂
Copy after login

#Reference documentation:
http://wiki.nginx.org/HttpLuaModuleZh#Core_constants ngx_lua official documentation

http://blog.csdn.net/imlsz/article/details/42915473 For the official Translation of the main content of the API

http://jinnianshilongnian.iteye.com/blog/2186448 Detailed examples of ngx_lua usage documentation
http://www.cnblogs.com/wangxusummer/p/4309007.html Module methods of ngx_lua A brief introduction


Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces the ngx_lua module API description, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does http status code 520 mean? What does http status code 520 mean? Oct 13, 2023 pm 03:11 PM

HTTP status code 520 means that the server encountered an unknown error while processing the request and cannot provide more specific information. Used to indicate that an unknown error occurred when the server was processing the request, which may be caused by server configuration problems, network problems, or other unknown reasons. This is usually caused by server configuration issues, network issues, server overload, or coding errors. If you encounter a status code 520 error, it is best to contact the website administrator or technical support team for more information and assistance.

What is http status code 403? What is http status code 403? Oct 07, 2023 pm 02:04 PM

HTTP status code 403 means that the server rejected the client's request. The solution to http status code 403 is: 1. Check the authentication credentials. If the server requires authentication, ensure that the correct credentials are provided; 2. Check the IP address restrictions. If the server has restricted the IP address, ensure that the client's IP address is restricted. Whitelisted or not blacklisted; 3. Check the file permission settings. If the 403 status code is related to the permission settings of the file or directory, ensure that the client has sufficient permissions to access these files or directories, etc.

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

Integration of Vue.js and Lua language to write lightweight embedded applications Integration of Vue.js and Lua language to write lightweight embedded applications Jul 31, 2023 pm 02:23 PM

The integration of Vue.js and Lua language to write lightweight embedded applications. In modern development, the front-end framework Vue.js and the scripting language Lua each have a wide range of applications. Vue.js is a progressive framework for building user interfaces, while Lua is a lightweight scripting language often used for embedded application and game development. This article will introduce how to integrate Vue.js with Lua language to write lightweight embedded applications, and provide code examples. First, we need to install Vue.j

How to use Nginx Proxy Manager to implement automatic jump from HTTP to HTTPS How to use Nginx Proxy Manager to implement automatic jump from HTTP to HTTPS Sep 26, 2023 am 11:19 AM

How to use NginxProxyManager to implement automatic jump from HTTP to HTTPS. With the development of the Internet, more and more websites are beginning to use the HTTPS protocol to encrypt data transmission to improve data security and user privacy protection. Since the HTTPS protocol requires the support of an SSL certificate, certain technical support is required when deploying the HTTPS protocol. Nginx is a powerful and commonly used HTTP server and reverse proxy server, and NginxProxy

Send POST request with form data using http.PostForm function Send POST request with form data using http.PostForm function Jul 25, 2023 pm 10:51 PM

Use the http.PostForm function to send a POST request with form data. In the http package of the Go language, you can use the http.PostForm function to send a POST request with form data. The prototype of the http.PostForm function is as follows: funcPostForm(urlstring,dataurl.Values)(resp*http.Response,errerror)where, u

Quick Application: Practical Development Case Analysis of PHP Asynchronous HTTP Download of Multiple Files Quick Application: Practical Development Case Analysis of PHP Asynchronous HTTP Download of Multiple Files Sep 12, 2023 pm 01:15 PM

Quick Application: Practical Development Case Analysis of PHP Asynchronous HTTP Download of Multiple Files With the development of the Internet, the file download function has become one of the basic needs of many websites and applications. For scenarios where multiple files need to be downloaded at the same time, the traditional synchronous download method is often inefficient and time-consuming. For this reason, using PHP to download multiple files asynchronously over HTTP has become an increasingly common solution. This article will analyze in detail how to use PHP asynchronous HTTP through an actual development case.

Common network communication and security problems and solutions in C# Common network communication and security problems and solutions in C# Oct 09, 2023 pm 09:21 PM

Common network communication and security problems and solutions in C# In today's Internet era, network communication has become an indispensable part of software development. In C#, we usually encounter some network communication problems, such as data transmission security, network connection stability, etc. This article will discuss in detail common network communication and security issues in C# and provide corresponding solutions and code examples. 1. Network communication problems Network connection interruption: During the network communication process, the network connection may be interrupted, which may cause

See all articles