Skip to content

安装

最小版本基于 nginx-1.21

添加 openresty 仓库

yum install yum-utils
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo

安装

yum install openresty

会被安装到 /usr/local/openresty

启动

systemctl start openresty

配置

nginx
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    # 关闭代码缓存,这样更改 lua 代码后旧不用重启 openresty 了,只在开发时关闭。
    lua_code_cache off;

    server {
        listen       3000;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        # 访问 /lua,执行 lua 代码。
        location /lua {
            default_type text/html;
            content_by_lua '
                ngx.say("<p>Hello, World!</p>")
            ';

            # 执行 lua 文件
            # content_by_lua_file conf/lua/hello.lua;
        }
    }
}

系统变量

获取 Nginx uri 中的指定的参数

nginx
location /nginx_var {
    default_type text/html;
    content_by_lua_block {
        # 获取参数 foo 的值
        ngx.say(ngx.var.arg_foo)
    }
}

获取 Nginx uri 中的所有参数

lua
local uri_args = ngx.req.get_uri_args()  

for k, v in pairs(uri_args) do  
    if type(v) == "table" then  
        ngx.say(k, " : ", table.concat(v, ", "), "<br/>")  
    else  
        ngx.say(k, ": ", v, "<br/>")  
    end  
end

获取 nginx 请求头信息

lua
local headers = ngx.req.get_headers()                         

ngx.say("Host : ", headers["Host"], "<br/>")  
ngx.say("user-agent : ", headers["user-agent"], "<br/>")  
ngx.say("user-agent : ", headers.user_agent, "<br/>")

for k,v in pairs(headers) do  
    if type(v) == "table" then  
        ngx.say(k, " : ", table.concat(v, ","), "<br/>")  
    else  
        ngx.say(k, " : ", v, "<br/>")  
    end  
end

获取 post 请求参数

lua
ngx.req.read_body()  

local post_args = ngx.req.get_post_args()  

for k, v in pairs(post_args) do  
    if type(v) == "table" then  
        ngx.say(k, " : ", table.concat(v, ", "), "<br/>")  
    else  
        ngx.say(k, ": ", v, "<br/>")  
    end  
end

获取 http 协议版本

lua
ngx.say("ngx.req.http_version : ", ngx.req.http_version(), "<br/>")

获取请求方法

lua
ngx.say("ngx.req.get_method : ", ngx.req.get_method(), "<br/>")

获取原始的请求头内容

lua
ngx.say("ngx.req.raw_header : ",  ngx.req.raw_header(), "<br/>")

获取请求体

lua
ngx.say("ngx.req.get_body_data() : ", ngx.req.get_body_data(), "<br/>")

在处理 http 请求时还可以使用

  • set_by_lua

    修改nginx变量

  • rewrite_by_lua

    修改uri

  • access_by_lua

    访问控制

  • header_filter_by_lua

    修改响应头

  • body_filter_by_lua

    修改响应体

  • log_by_lua

    日志