标签 nginx 下的文章

-- 读取所有url参数
local arg = ngx.req.get_uri_args()
ngx.say("读取的参数类型是:"..type(arg)) -- table

-- 遍历table并打印参数
for k,v in pairs(arg) do
    ngx.say("[GET ] key:", k, " v:", v)
end

-- 获取请求URI
local req_uri = ngx.var.request_uri

-- 获取请求域名
local req_host = ngx.var.host

-- 获取请求方法
local req_method = ngx.var.request_method

-- 只取name,取不到就是nil
ngx.say(arg["name"])

-- 获取cookie中的pcip值
local pcip = ngx.var.cookie_pcip

-- get请求
local getParams = ngx.req.get_uri_args()

-- post请求
ngx.req.read_body()
local postParams = ngx.req.get_post_args()

-- json参数
ngx.req.read_body()
local jsonBody = ngx.req.get_body_data()

-- 获取header
local headers = ngx.req.get_headers()
local foo = ngx.header.x_foo
local foo = ngx.header["X-Foo"]
ngx.req.raw_header(true)

local h = ngx.resp.get_headers()
for k, v in pairs(h) do
end

-- 设置header
ngx.header.content_type = 'text/plain';
ngx.header['Set-Cookie'] = {'a=32; path=/', 'b=4; path=/'}

1)使用ngx.location.capture

返回一个包含四个元素的 Lua 表 (res.status, res.header, res.body, 和 res.truncated)。
因为 Nginx 内核限制,子请求不允许类似 @foo 命名 location。请使用标准 location,并设置 internal 指令,仅服务内部请求。
有以下参数:
method, body, args, ctx, vars, copy_all_vars, share_all_vars, always_forward_body。

location /product {
    internal;
    echo "商品请求";
}

location /order {
    content_by_lua_block {
        ngx.req.read_body()
        local args, err = ngx.req.get_post_args(100)
        -- 返回 res.status, res.header, res.body, res.truncated
        local res = ngx.location.capture("/product", {
            method = ngx.HTTP_GET,
            args = {a = args.a, b = args.b}
        })
        ngx.say(res.status)
        ngx.say(res.body)
    }
}

2)使用ngx.location.capture_multi

local res1, res2 = ngx.location.capture_multi({
    {"/sum", {args={a=3, b=4}}},
    {"/sub", {args={a=3, b=4}}}
})
ngx.say(res1.status, res1.body)
ngx.say(res2.status, res2.body)


res1, res2, res3 = ngx.location.capture_multi{
    { "/foo", { args = "a=3&b=4" } },
    { "/bar" },
    { "/baz", { method = ngx.HTTP_POST, body = "hello" } },
}

if res1.status == ngx.HTTP_OK then
end

if res2.body == "BLAH" then
end


local reqs = {}
table.insert(reqs, { "/mysql" })
table.insert(reqs, { "/postgres" })
table.insert(reqs, { "/redis" })
table.insert(reqs, { "/memcached" })
local resps = { ngx.location.capture_multi(reqs) }
for i, resp in ipairs(resps) do
    -- process the response table "resp"
end

1)安装lua-resty-http
opm get agentzh/lua-resty-http

2)编辑nginx.conf,在http块增加以下配置。
resolver 114.114.114.114 8.8.8.8;
lua_ssl_verify_depth 2;
lua_ssl_trusted_certificate '/etc/ssl/certs/ca-certificates.crt';

备注:如果/etc/ssl/certs/ca-certificates.crt不存在,则安装ca-certificates(例:apt-get install ca-certificates)。

3)代码示例

local http = require "resty.http"
local json = require "cjson"

local httpc = http:new()
local res, err = httpc:request_uri("http://127.0.0.1:80/", {
    method = "POST/GET",
    query = "a=1&b=2",
    body = "c=3&d=4",
    path = "/",
    headers = {
        ["Content-Type"] = "application/json",
        -- ["Content-Type"] = "application/x-www-form-urlencoded",
        ["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
    },
    ssl_verify = false,
})

if err ~= nil then
    ngx.log(ngx.ERR, "http request err:", err)
    return ngx.exit(0)
end

if 200 ~= res.status then
    ngx.exit(res.status)
end

local jsondata = json.decode(res.body)["data"]

httpc:close()
-- httpc:set_keepalive()

1)安装依赖

yum install -y make cmake gcc gcc-c++ autoconf automake libpng-devel libjpeg-devel zlib libxml2-devel ncurses-devel bison libtool-ltdl-devel libiconv libmcrypt mhash mcrypt pcre-devel openssl-devel freetype-devel libcurl-devel lua-devel readline-devel curl wget

2)源码构建

wget https://openresty.org/download/openresty-1.21.4.1.tar.gz
tar -xzvf openresty-1.21.4.1.tar.gz
cd openresty-1.21.4.1/
./configure --with-pcre-jit --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-http_v2_module --without-mail_pop3_module --without-mail_imap_module --without-mail_smtp_module --with-http_stub_status_module --with-http_realip_module --with-http_addition_module --with-http_auth_request_module --with-http_secure_link_module --with-http_random_index_module --with-http_gzip_static_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-threads --with-compat --with-stream --with-http_ssl_module
sudo make
sudo make install

3)修改nginx.conf

user  nobody;
worker_processes  auto;
worker_rlimit_nofile 65535;
 
error_log  /var/log/nginx/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
pid        /run/nginx.pid;
 
events {
    worker_connections  65535;
    multi_accept on;
    use epoll;
}
 
http {
    include       mime.types;
    default_type  application/octet-stream;
    server_tokens off;
 
    server_names_hash_max_size 1024;
#    server_names_hash_bucket_size 128;
 
   set_real_ip_from 100.125.0.0/16;
    real_ip_header X-Forwarded-For;
 
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
 
    log_format  main    '$remote_addr - $remote_user [$time_local] "$request" '
            '$status $body_bytes_sent "$http_referer" '
            '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log  /var/log/nginx/access.log  main;
 
    sendfile    on;
    tcp_nopush  on;
    tcp_nodelay on;
    types_hash_max_size 4096;
 
    #keepalive_timeout  0;
    keepalive_timeout  65;
 
    gzip  on;
#    gzip_static on;
    gzip_min_length 1k;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_buffers 16 64k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript application/xml application/xml+rss text/javascript application/x-javascript;
 
    include /etc/nginx/conf.d/*.conf;
 
    server {
        listen       80;
        server_name  localhost;
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        location / {
            root   html;
            index  index.html index.htm;
        }
 
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}