OpenResty安裝、配置與使用
OpenResty簡介
OpenResty 是一個基於 Nginx 與 Lua 的高性能 Web 平臺,其內部集成了大量精良的 Lua 庫、第三方模塊以及大多數的依賴項。用於方便地搭建能夠處理超高併發、擴展性極高的動態 Web 應用、Web 服務和動態網關。
Lua簡介
Lua是一個簡潔、輕量、可擴展的程序設計語言,其設計目的是爲了嵌入應用程序中,從而爲應用程序提供靈活的擴展和定製功能。Lua由標準C編寫而成,代碼簡潔優美,幾乎在所有操作系統和平臺上都可以編譯,運行。
OpenResty安裝
1.安裝依賴庫
yum install readline-devel pcre-devel openssl-devel gcc
2.下載及安裝OpenResty
wget https://openresty.org/download/openresty-1.9.15.1.tar.gz
tar xvf openresty-1.9.15.1.tar.gz
cd openresty-1.9.15.1
./configure --with-luajit && make && make install
激活LuaJIT
組件被用於構建 OpenResty。所有的組件可以被激活或禁止。 大部組件默認是激活的,也有部件不是。 LuaJIT、 DrizzleNginxModule、PostgresNginxModule和IconvNginxModule 默認是沒有激活的。您需要通過以下選項在編譯 OpenResty的時候將它們各自激活, --with-luajit、 --with-http_drizzle_module、 --with-http_postgres_module和 --with-http_iconv_module 。
安裝好的OpenResty
從上圖可以看到,openresty在/usr/local目錄下
OpenResty啓動
通過下述方式啓動Nginx。如果沒有任何輸出,說明啓動成功,-p 指定我們的項目目錄,-c 指定配置文件。
/usr/local/openresty/nginx/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf
/usr/local/openresty/nginx/sbin/nginx -p ‘pwd’ -c /usr/local/openresty/nginx/conf/nginx.conf
爲openresty下的nginx建立軟鏈(非必需)
ln -s /usr/local/openresty/nginx/sbin/nginx /usr/sbin/nginx
則可使用如下方式啓動
/usr/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf
在瀏覽器中訪問:
OpenResty配置Lua
由於原生的Nginx日誌沒有resp_body這一選項,通過在nginx.conf中添加Lua腳本的方式定義resp_body。
vim /usr/local/openresty/nginx/conf/nginx.conf
http {
include mime.types;
default_type application/octet-stream;
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 log_resp_body '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$request_time $bytes_sent $request_length "$request_body" "$resp_body"';
access_log logs/access.log main;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
access_log logs/access.index.log log_resp_body;
lua_need_request_body on;
set $resp_body "";
body_filter_by_lua '
local resp_body = string.sub(ngx.arg[1], 1, 1000)
ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body
if ngx.arg[2] then
ngx.var.resp_body = ngx.ctx.buffered
end
';
location / {
root html;
index index.html index.htm;
}
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
檢測Nginx配置是否正確
/usr/sbin/nginx -t
重啓Nginx
/usr/sbin/nginx -s reload
驗證Lua配置是否成功
tail -f access.log
tail -f access.index.log