記住一點:nginx配置文件不少坑來源自你的空格少了或多了。html
OpenResty® 是一個基於 Nginx 與 Lua 的高性能 Web 平臺,其內部集成了大量精良的 Lua 庫、第三方模塊以及大多數的依賴項。用於方便地搭建可以處理超高併發、擴展性極高的動態 Web 應用、Web 服務和動態網關。nginx
OpenResty® 經過匯聚各類設計精良的 Nginx 模塊(主要由 OpenResty 團隊自主開發),從而將 Nginx 有效地變成一個強大的通用 Web 應用平臺。這樣,Web 開發人員和系統工程師可使用 Lua 腳本語言調動 Nginx 支持的各類 C 以及 Lua 模塊,快速構造出足以勝任 10K 乃至 1000K 以上單機併發鏈接的高性能 Web 應用系統。git
OpenResty® 的目標是讓你的Web服務直接跑在 Nginx 服務內部,充分利用 Nginx 的非阻塞 I/O 模型,不單單對 HTTP 客戶端請求,甚至於對遠程後端諸如 MySQL、PostgreSQL、Memcached 以及 Redis 等都進行一致的高性能響應。github
若是你的系統是 Centos 或 RedHat 可使用如下命令:web
yum install readline-devel pcre-devel openssl-devel
接下咱們能夠在官方(https://openresty.org/cn/)下載最新的 OpenResty 源碼包並解壓編譯安裝:shell
wget https://openresty.org/download/ngx_openresty-1.9.7.1.tar.gz # 下載 tar xzvf ngx_openresty-1.9.7.1.tar.gz # 解壓 cd ngx_openresty-1.9.7.1/ ./configure make make install
默認狀況下程序會被安裝到 /usr/local/openresty 目錄,你可使用 ./configure --help 查看更多的配置選項。後端
安裝成功後,咱們就可使用 openresty 直接輸出 html 頁面。centos
首先咱們能夠建立一個工做目錄:api
mkdir /home/www cd /home/www/ mkdir logs/ conf/
其中 logs 目錄用於存放日誌,conf 用於存放配置文件。cookie
接着,咱們在 conf 目錄下建立一個 nginx.conf 文件 代碼以下:
worker_processes 1; error_log logs/error.log; events { worker_connections 1024; } http { server { listen 9000; location / { default_type text/html; content_by_lua ' ngx.say("<p>Hello, World!</p>") '; } } }
若是你熟悉 nginx 的配置,應該對以上代碼就很熟悉。這裏咱們將 html 代碼直接寫在了配置文件中。
默認狀況下 openresty 安裝在 /usr/local/openresty 目錄中,啓動命令爲:
/usr/local/openresty/nginx/sbin/nginx -p /home/www/ -c conf/nginx.conf
若是沒有任何輸出,說明啓動成功,-p 指定咱們的項目目錄,-c 指定配置文件。
接下來咱們可使用 curl 來測試是否可以正常範圍:
curl http://localhost:9000/
輸出結果爲:
<p>Hello, World!</p>
在 HelloWorld 實例中,咱們直接在 nginx.conf 中寫Lua腳本,不少時候,Lua腳本是一個文件。下面演示使用 content_by_lua_file 指令調用Lua腳本文件。
在conf文件夾下建立helloworld.lua:
ngx.say("<p>Hello, World!</p>")
修改你的 nginx.conf 文件內容爲:
worker_processes 1; error_log logs/error.log; events { worker_connections 1024; } http { server { listen 9000; location / { default_type text/html; content_by_lua_file 'conf/helloworld.lua'; } } }
中止已啓動的nginx進程:
killall -9 nginx
啓動nginx進程:
/usr/local/openresty/nginx/sbin/nginx -p /home/www/ -c conf/nginx.conf
接下來咱們可使用 curl 來測試是否可以正常範圍:
curl 'localhost:9000'
輸出結果爲:
<p>Hello, World!</p>
使用 set_by_lua 指定能夠用相似調用函數的形式去調用Lua腳本。語法:
set_by_lua $res <lua-script-str> [$arg1 $arg2 ...]
修改你的conf/nginx.conf文件:
worker_processes 1; error_log logs/error.log; events { worker_connections 1024; } http { server { listen 9000; location / { default_type text/html; set_by_lua $res ' local a = tonumber(ngx.arg[1]) local b = tonumber(ngx.arg[2]) return a+b' $arg_a $arg_b; echo $res; } } }
中止已啓動的nginx進程,命令:
killall -9 nginx
啓動nginx進程:
/usr/local/openresty/nginx/sbin/nginx -p /home/www/ -c conf/nginx.conf
接下來咱們可使用 curl 來測試是否可以正常範圍:
curl 'localhost:9000/?a=2&b=5'
輸出結果爲:
7
set_by_lua_file能夠調用本地Lua腳本文件。語法與set_by_lua相同:
set_by_lua_file $res <lua-script-str> [$arg1 $arg2 ...]
在conf文件夾下建立hello.lua文件:
local a = tonumber(ngx.arg[1]) local b = tonumber(ngx.arg[2]) return a+b
在conf文件夾下建立nginx_lua.conf文件:
worker_processes 1; error_log logs/error.log; events { worker_connections 1024; } http { server { listen 9000; location = / { default_type text/html; set_by_lua_file $res "conf/hello.lua" $arg_a $arg_b; echo $res; } } }
啓動nginx進程:
/usr/local/openresty/nginx/sbin/nginx -p /home/www/ -c conf/nginx_lua.conf
接下來咱們可使用 curl 來測試是否可以正常範圍:
curl 'localhost:9000/?a=2&b=5'
輸出結果爲:
7
在conf文件夾下建立nginx.conf文件:
worker_processes 1; error_log logs/error.log; events { worker_connections 1024; } http { server { listen 9000; location / { set $a $host; set $b 'hello world'; default_type text/html; content_by_lua_file 'conf/hello.lua'; } } }
在conf文件夾下建立hello.lua:
local var = ngx.var ngx.say("ngx.var.a : ", var.a, "<br/>") ngx.say("ngx.var.b : ", var.b, "<br/>") ngx.say("<br/>")
啓動nginx進程:
/usr/local/openresty/nginx/sbin/nginx -p /home/www/ -c conf/nginx_lua.conf
接下來咱們可使用 curl 來測試是否可以正常範圍:
curl 'localhost:9000'
輸出結果爲:
ngx.var.a : localhost<br/> ngx.var.b : hello world<br/>
如今已經學會了content_by_lua 與 set_by_lua 指令,其它相似的指令還有不少,那麼這些指令都是有什麼區別呢?主要區別是指令的運行週期不一樣,如圖所示。(圖片來源於網絡)
指令 | 所到處理階段 | 使用範圍 | 解釋 |
---|---|---|---|
init_by_lua init_by_lua_file |
loading-config | http | nginx Master進程加載配置時執行;一般用於初始化全局配置/預加載Lua模塊 |
init_worker_by_lua init_worker_by_lua_file |
starting-worker | http | 每一個Nginx Worker進程啓動時調用的計時器,若是Master進程不容許則只會在init_by_lua以後調用;一般用於定時拉取配置/數據,或者後端服務的健康檢查 |
set_by_lua set_by_lua_file |
rewrite | server,server if,location,location if | 設置nginx變量,能夠實現複雜的賦值邏輯;此處是阻塞的,Lua代碼要作到很是快; |
rewrite_by_lua rewrite_by_lua_file |
rewrite tail | http,server,location,location if | rrewrite階段處理,能夠實現複雜的轉發/重定向邏輯; |
access_by_lua access_by_lua_file |
access tail | http,server,location,location if | 請求訪問階段處理,用於訪問控制 |
content_by_lua content_by_lua_file |
content | location,location if | 內容處理器,接收請求處理並輸出響應 |
header_filter_by_lua header_filter_by_lua_file |
output-header-filter | http,server,location,location if | 設置header和cookie |
body_filter_by_lua body_filter_by_lua_file |
output-body-filter | http,server,location,location if | 對響應數據進行過濾,好比截斷、替換。 |
log_by_lua log_by_lua_file |
log | http,server,location,location if | log階段處理,好比記錄訪問量/統計平均響應時間 |
將下面的lua腳本複製到你的content_by_lua_file指定的lua文件中便可。
--請求頭 local headers = ngx.req.get_headers() ngx.say("headers begin", "<br/>") 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 ngx.say("headers end", "<br/>") ngx.say("<br/>") --get請求uri參數 ngx.say("uri args begin", "<br/>") 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 ngx.say("uri args end", "<br/>") ngx.say("<br/>") --post請求參數 ngx.req.read_body() ngx.say("post args begin", "<br/>") 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 ngx.say("post args end", "<br/>") ngx.say("<br/>") --請求的http協議版本 ngx.say("ngx.req.http_version : ", ngx.req.http_version(), "<br/>") --請求方法 ngx.say("ngx.req.get_method : ", ngx.req.get_method(), "<br/>") --原始的請求頭內容 ngx.say("ngx.req.raw_header : ", ngx.req.raw_header(), "<br/>") --請求的body內容體 ngx.say("ngx.req.get_body_data() : ", ngx.req.get_body_data(), "<br/>") ngx.say("<br/>") local request_uri = ngx.var.request_uri; ngx.say("request_uri : ", request_uri, "<br/>"); --解碼 ngx.say("decode request_uri : ", ngx.unescape_uri(request_uri), "<br/>"); --MD5 ngx.say("ngx.md5 : ", ngx.md5("123"), "<br/>") --http time ngx.say("ngx.http_time : ", ngx.http_time(ngx.time()), "<br/>") --當前時間 ngx.update_time() local now = ngx.now() ngx.say("nowTime : ", now, "<br/>")
訪問 http://127.0.0.1:9000/?a=8&b=55 ,手動輸入兩個Cookie,輸出結果:
headers begin Host : 127.0.0.1:9000 user-agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36 user-agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36 accept-language : zh-CN,zh;q=0.9 connection : keep-alive accept : text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 cache-control : max-age=0 host : 127.0.0.1:9000 cookie : hello=world; Heelo=Sdd accept-encoding : gzip, deflate upgrade-insecure-requests : 1 user-agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36 headers end uri args begin b: 55 a: 8 uri args end post args begin post args end ngx.req.http_version : 1.1 ngx.req.get_method : GET ngx.req.raw_header : GET /?a=8&b=55 HTTP/1.1 Host: 127.0.0.1:9000 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Cookie: hello=world; Heelo=Sdd ngx.req.get_body_data() : nil request_uri : /?a=8&b=55 decode request_uri : /?a=8&b=55 ngx.md5 : 202cb962ac59075b964b07152d234b70 ngx.http_time : Mon, 29 Apr 2019 14:53:17 GMT
Lua如何調用系統shell呢?
--調用系統命令 local t = io.popen('cat /home/www/conf/hello.lua') local a = t:read("*all") t:close() ngx.say(a)
Lua發送Http請求,默認是不支持的,須要引入第三方庫。也就是下方這個Github地址的兩個文件:http.lua 和 http_headers.lua 。
Github:https://github.com/ledgetech/lua-resty-http/tree/master/lib/resty
流程和上方的Demo相似,不一樣的是,須要在你的 lua 文件中寫入一行代碼:
local http = require "resty.http"
啓動你的 nginx ,命令同上。使用 curl 命令測試訪問,查看 logs 目錄下的 error.log 文件:
2019/04/30 14:23:21 [error] 7093#0: *1 lua entry thread aborted: runtime error: /home/www/conf/helloworld.lua:95: module 'resty.http' not found: no field package.preload['resty.http'] no file '/usr/local/openresty/lualib/resty/http.lua' no file '/usr/local/openresty/lualib/resty/http/init.lua' no file './resty/http.lua' no file '/usr/local/openresty/luajit/share/luajit-2.1.0-beta1/resty/http.lua' no file '/usr/local/share/lua/5.1/resty/http.lua' no file '/usr/local/share/lua/5.1/resty/http/init.lua' no file '/usr/local/openresty/luajit/share/lua/5.1/resty/http.lua' no file '/usr/local/openresty/luajit/share/lua/5.1/resty/http/init.lua' no file '/usr/local/openresty/lualib/resty/http.so' no file './resty/http.so' no file '/usr/local/lib/lua/5.1/resty/http.so' no file '/usr/local/openresty/luajit/lib/lua/5.1/resty/http.so' no file '/usr/local/lib/lua/5.1/loadall.so' no file '/usr/local/openresty/lualib/resty.so' no file './resty.so' no file '/usr/local/lib/lua/5.1/resty.so' no file '/usr/local/openresty/luajit/lib/lua/5.1/resty.so' no file '/usr/local/lib/lua/5.1/loadall.so'
咱們只須要在錯誤日誌的第一個目錄下添加上面兩個http模塊的lua文件便可。目錄:
/usr/local/openresty/lualib/resty/
接下來就是重啓你的nginx,再次訪問,發現不報錯了。
local http = require "resty.http" local function http_post_client(url, timeout) local httpc = http.new() timeout = timeout or 30000 httpc:set_timeout(timeout) local res, err_ = httpc:request_uri(url, { method = "GET", headers = { ["Content-Type"] = "application/x-www-form-urlencoded", } }) httpc:set_keepalive(5000, 100) --httpc:close() return res, err_ end
local http = require "resty.http" local function http_post_client(url,body,timeout) local httpc = http.new() timeout = timeout or 30000 httpc:set_timeout(timeout) local res, err_ = httpc:request_uri(url, { method = "POST", body = body, headers = { ["Content-Type"] = "application/x-www-form-urlencoded", } }) httpc:set_keepalive(5000, 100) httpc:close() if not res then return nil, err_ else if res.status == 200 then return res.body, err_ else return nil, err_ end end end
--get local resp, err = http_post_client("http://127.0.0.1/index.html?name=test",3000) --post local body = {"name" = "test"} local resp, err = http_post_client("http://127.0.0.1/index.html?name=test",body,3000)
https://blog.csdn.net/qq_21860077/article/details/83623888
Nginx API for Lua:http://www.javashuo.com/article/p-sgvvczhq-dc.html