一、安裝nginx
安裝nginx教程就不具體介紹了,網(wǎng)上教程很多,隨便搜幾個就ok。
二、安裝openresty
推薦安裝openresty。openresty是一個打包程序,包含大量的第三方Nginx模塊,包括lua。咱們現(xiàn)在主要是使用其中的ngx_lua模塊來幫助nginx日志記錄response。
1、安裝openresty依賴
ubuntu安裝:
# sudo apt-get install libreadline-dev libncurses5-dev libpcre3-dev \
libssl-dev perl make build-essential
centos安裝:
# yum install readline-devel pcre-devel openssl-devel gcc
2、下載openresty源碼:
# wget http://openresty.org/download/openresty-1.9.7.4.tar.gz
3、解壓
# tar xf openresty-1.9.7.4.tar.gz
4、編譯安裝
# cdopenresty-1.9.7.4
# ./configure --prefix=/opt/openresty \
--with-luajit \
--without-http_redis2_module \
--with-http_iconv_module
# make && make install
此方法本次測試暫時不可用,請參考官方安裝文檔:http://openresty.org/cn/linux-packages.html
5、運行測試
-- 1. 修改配置文件如下:
$ cat /opt/openresty/nginx/conf/nginx.conf
worker_processes 1;
error_log logs/error.log info;
events {
worker_connections 1024;
}
http {
server {
listen 8003;
location / {
content_by_lua 'ngx.say("hello world.")';
}
}
}
-- 2. 啟動nginx
$ /opt/openresty/nginx/sbin/nginx
-- 3. 檢查nginx
$ curl http://127.0.0.1:8003/
hello world.
三、配置nginx.conf
worker_processes 1;
error_log logs/error.log info;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr | $remote_user | [$time_local] | '
'"$request" | $status | $body_bytes_sent | '
'"$http_referer" | "$http_user_agent" | $request_time | '
'"$request_body" | "$resp_body"';
access_log logs/access.log main;
upstream bankend {
server 192.168.136.102:9090;
server 192.168.136.103:9090;
}
server {
listen 8000;
server_name localhost;
set $resp_body "";
location / {
proxy_pass http://bankend;
lua_need_request_body on;
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
';
}
}
}
四、運行
啟動nginx后,發(fā)送請求,nginx的日志這個時候已經(jīng)可以正常記錄請求和相應數(shù)據(jù)了。