此处用到lua-nginx-module openresty是自带的~ nginx需要安装库
备注: 由于此处需要记录同类型的两个日志(visit_log.log和share_log.log)所以用到 ngx.var.conf进行传参~ 具体赋值方法如下:
Nginx配置
location /visit.gif {
set $conf 'visit';
content_by_lua_file conf/data.lua;
}
location /share.gif {
set $conf 'share';
content_by_lua_file conf/data.lua;
}
data.lua
local file_name
local conf = ngx.var.conf -- 在外部设置了ngx.var.conf变量 在里面读出来
if(conf == 'visit')
then
file_name = '/usr/local/openresty/nginx/logs/visit_log.log'
elseif(conf == 'share')
then
file_name = '/usr/local/openresty/nginx/logs/share_log.log'
end
--[[
-- 写文件
-- fileName 文件名
-- content 写入内容
--]]
function write_content(fileName, content)
local f = assert(io.open(fileName,'a'))
f:write(content)
f:close()
end
-- 打开request body的读取
ngx.req.read_body()
local s
local extend = '&ip='..ngx.var.remote_addr..'&userAgent='..ngx.req.get_headers()["User-Agent"]..'\n' -- 将要扩展的在这里拼接
--判断是POST还是GET
if(ngx.req.get_method() == 'POST')
then
s = ngx.var.request_body..extend
if (nil ~= s)
then
-- 写入对应文件
write_content(file_name, s)
end
else
s = ngx.var.args..extend
if (nil ~= s)
then
write_content(file_name, s)
end
end