---
title: "lua 集成Niginx 内部变量函数集总"
author: "fredlong"
date: "2017-07-10T11:35:35Z"
tags: []
categories: ["开源软件"]
slug: "lua-niginx"
draft: false
lastmod: "2017-07-10T11:35:35Z"
id: 2383847
url: "https://fredlong.iteye.com/blog/2383847"
---

Nginx提供了很多内置的变量,如:

- $arg\_PARAMETER 这个变量包含在查询字符串时GET请求PARAMETER的值。
- $args 这个变量等于请求行中的参数。
- $binary\_remote\_addr 二进制码形式的客户端地址。
- $body\_bytes\_sent 传送页面的字节数
- $content\_length 请求头中的Content-length字段。
- $content\_type 请求头中的Content-Type字段。
- $cookie\_COOKIE cookie COOKIE的值。
- $document\_root 当前请求在root指令中指定的值。
- $document\_uri 与$uri相同。
- $host 请求中的主机头字段，如果请求中的主机头不可用，则为服务器处理请求的服务器名称。
- $is\_args 如果$args设置，值为"?"，否则为""。
- $limit\_rate 这个变量可以限制连接速率。
- $nginx\_version 当前运行的nginx版本号。
- $query\_string 与$args相同。
- $remote\_addr 客户端的IP地址。
- $remote\_port 客户端的端口。
- $remote\_user 已经经过Auth Basic Module验证的用户名。
- $request\_filename 当前连接请求的文件路径，由root或alias指令与URI请求生成。
- $request\_body 这个变量（0.7.58+）包含请求的主要信息。在使用proxy\_pass或fastcgi\_pass指令的location中比较有意义。
- $request\_body\_file 客户端请求主体信息的临时文件名。
- $request\_completion 未知。
- $request\_method 这个变量是客户端请求的动作，通常为GET或POST。包括0.8.20及之前的版本中，这个变量总为main request中的动作，如果当前请求是一个子请求，并不使用这个当前请求的动作。
- $request\_uri 这个变量等于包含一些客户端请求参数的原始URI，它无法修改，请查看$uri更改或重写URI。
- $scheme 所用的协议，比如http或者是https，比如rewrite ^(.+)$ $scheme://example.com$1 redirect;
- $server\_addr 服务器地址，在完成一次系统调用后可以确定这个值，如果要绕开系统调用，则必须在listen中指定地址并且使用bind参数。
- $server\_name 服务器名称。
- $server\_port 请求到达服务器的端口号。
- $server\_protocol 请求使用的协议，通常是HTTP/1.0或HTTP/1.1。
- $uri 请求中的当前URI(不带请求参数，参数位于$args)，可以不同于浏览器传递的$request\_uri的值，它可以通过内部重定向，或者使用index指令进行修改。

另外：HTTP\_X\_FORWARDED\_FOR是透过代理服务器取得客户端的真实IP地址，有些用此方法读取到的仍然是代理服务器的IP。还有一点需要注意的是：如果客户端没有通过代理服务器来访问，那么用 HTTP\_X\_FORWARDED\_FOR 取到的值将是空的。

 

**ngx\_lua 模块提供的指令和API等：**

  指令名称 说明 lua\_use\_default\_type 是否使用default\_type指令定义的Content-Type默认值 lua\_code\_cache \*\_by\_lua\_file文件是否cache lua\_regex\_cache\_max\_entries   lua\_regex\_match\_limit   lua\_package\_path 用Lua写的lua外部库路径（.lua文件） lua\_package\_cpath 用C写的lua外部库路径（.so文件） init\_by\_lua master进程启动时挂载的lua代码 init\_by\_lua\_file   init\_worker\_by\_lua worker进程启动时挂载的lua代码，常用来执行一些定时器任务 init\_worker\_by\_lua\_file   set\_by\_lua 设置变量 set\_by\_lua\_file   content\_by\_lua handler模块 content\_by\_lua\_file   rewrite\_by\_lua   rewrite\_by\_lua\_file   access\_by\_lua   access\_by\_lua\_file   header\_filter\_by\_lua header filter模块 header\_filter\_by\_lua\_file   body\_filter\_by\_lua body filter模块，ngx.arg\[1]代表输入的chunk，ngx.arg\[2]代表当前chunk是否为last body\_filter\_by\_lua\_file   log\_by\_lua   log\_by\_lua\_file   lua\_need\_request\_body 是否读请求体，跟ngx.req.read\_body()函数作用类似 lua\_shared\_dict 创建全局共享的table（多个worker进程共享） lua\_socket\_connect\_timeout TCP/unix 域socket对象connect方法的超时时间 lua\_socket\_send\_timeout TCP/unix 域socket对象send方法的超时时间 lua\_socket\_send\_lowat 设置cosocket send buffer的low water值 lua\_socket\_read\_timeout TCP/unix 域socket对象receive方法的超时时间 lua\_socket\_buffer\_size cosocket读buffer大小 lua\_socket\_pool\_size cosocket连接池大小 lua\_socket\_keepalive\_timeout cosocket长连接超时时间 lua\_socket\_log\_errors 是否打开cosocket错误日志 lua\_ssl\_ciphers   lua\_ssl\_crl   lua\_ssl\_protocols   lua\_ssl\_trusted\_certificate   lua\_ssl\_verify\_depth   lua\_http10\_buffering   rewrite\_by\_lua\_no\_postpone   lua\_transform\_underscores\_in\_response\_headers   lua\_check\_client\_abort 是否监视client提前关闭请求的事件，如果打开监视，会调用ngx.on\_abort()注册的回调 lua\_max\_pending\_timers   lua\_max\_running\_timers  

 

 

 

  table 说明 ngx.arg 指令参数，如跟在content\_by\_lua\_file后面的参数 ngx.var 变量，ngx.var.VARIABLE引用某个变量 ngx.ctx 请求的lua上下文 ngx.header 响应头，ngx.header.HEADER引用某个头 ngx.status 响应码     API 说明 ngx.log 输出到error.log print 等价于 ngx.log(ngx.NOTICE, ...) ngx.send\_headers 发送响应头 ngx.headers\_sent 响应头是否已发送 ngx.resp.get\_headers 获取响应头 ngx.timer.at 注册定时器事件 ngx.is\_subrequest 当前请求是否是子请求 ngx.location.capture 发布一个子请求 ngx.location.capture\_multi 发布多个子请求 ngx.exec   ngx.redirect   ngx.print 输出响应 ngx.say 输出响应，自动添加'\\n' ngx.flush 刷新响应 ngx.exit 结束请求 ngx.eof   ngx.sleep 无阻塞的休眠（使用定时器实现） ngx.get\_phase   ngx.on\_abort 注册client断开请求时的回调函数 ndk.set\_var.DIRECTIVE   ngx.req.start\_time 请求的开始时间 ngx.req.http\_version 请求的HTTP版本号 ngx.req.raw\_header 请求头（包括请求行） ngx.req.get\_method 请求方法 ngx.req.set\_method 请求方法重载 ngx.req.set\_uri 请求URL重写 ngx.req.set\_uri\_args   ngx.req.get\_uri\_args 获取请求参数 ngx.req.get\_post\_args 获取请求表单 ngx.req.get\_headers 获取请求头 ngx.req.set\_header   ngx.req.clear\_header   ngx.req.read\_body 读取请求体 ngx.req.discard\_body 扔掉请求体 ngx.req.get\_body\_data   ngx.req.get\_body\_file   ngx.req.set\_body\_data   ngx.req.set\_body\_file   ngx.req.init\_body   ngx.req.append\_body   ngx.req.finish\_body   ngx.req.socket   ngx.escape\_uri 字符串的url编码 ngx.unescape\_uri 字符串url解码 ngx.encode\_args 将table编码为一个参数字符串 ngx.decode\_args 将参数字符串编码为一个table ngx.encode\_base64 字符串的base64编码 ngx.decode\_base64 字符串的base64解码 ngx.crc32\_short 字符串的crs32\_short哈希 ngx.crc32\_long 字符串的crs32\_long哈希 ngx.hmac\_sha1 字符串的hmac\_sha1哈希 ngx.md5 返回16进制MD5 ngx.md5\_bin 返回2进制MD5 ngx.sha1\_bin 返回2进制sha1哈希值 ngx.quote\_sql\_str SQL语句转义 ngx.today 返回当前日期 ngx.time 返回UNIX时间戳 ngx.now 返回当前时间 ngx.update\_time 刷新时间后再返回 ngx.localtime   ngx.utctime   ngx.cookie\_time 返回的时间可用于cookie值 ngx.http\_time 返回的时间可用于HTTP头 ngx.parse\_http\_time 解析HTTP头的时间 ngx.re.match   ngx.re.find   ngx.re.gmatch   ngx.re.sub   ngx.re.gsub   ngx.shared.DICT   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   ngx.socket.udp   udpsock:setpeername   udpsock:send   udpsock:receive   udpsock:close   udpsock:settimeout   ngx.socket.tcp   tcpsock:connect   tcpsock:sslhandshake   tcpsock:send   tcpsock:receive   tcpsock:receiveuntil   tcpsock:close   tcpsock:settimeout   tcpsock:setoption   tcpsock:setkeepalive   tcpsock:getreusedtimes   ngx.socket.connect   ngx.thread.spawn   ngx.thread.wait   ngx.thread.kill   coroutine.create   coroutine.resume   coroutine.yield   coroutine.wrap   coroutine.running   coroutine.status   ngx.config.debug 编译时是否有 --with-debug选项 ngx.config.prefix 编译时的 --prefix选项 ngx.config.nginx\_version 返回nginx版本号 ngx.config.nginx\_configure 返回编译时 ./configure的命令行选项 ngx.config.ngx\_lua\_version 返回ngx\_lua模块版本号 ngx.worker.exiting 当前worker进程是否正在关闭（如reload、shutdown期间） ngx.worker.pid 返回当前worker进程的pid             常量 说明 Core constants ngx.OK (0)  
ngx.ERROR (-1)  
ngx.AGAIN (-2)  
ngx.DONE (-4)  
ngx.DECLINED (-5)  
ngx.nil HTTP method constants 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 constants 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.STDERR  
ngx.EMERG  
ngx.ALERT  
ngx.CRIT  
ngx.ERR  
ngx.WARN  
ngx.NOTICE  
ngx.INFO  
ngx.DEBUG