【发布时间】:2016-07-26 04:49:50
【问题描述】:
在 Nginx + Lua 中文件输出有问题。我选择了LUA,因为nginx的逻辑相当复杂,基于referrer或者子域等。
有像 /img/am1/s/1.jpg 这样的请求,我需要检查 /somepath/am1/1.jpg 中是否存在文件。如果存在则输出,否则代理请求到后端。
【问题讨论】:
在 Nginx + Lua 中文件输出有问题。我选择了LUA,因为nginx的逻辑相当复杂,基于referrer或者子域等。
有像 /img/am1/s/1.jpg 这样的请求,我需要检查 /somepath/am1/1.jpg 中是否存在文件。如果存在则输出,否则代理请求到后端。
【问题讨论】:
好的,找到了
content_by_lua '
local file = "/path..."
local f = io.open(file, "rb")
local content = f:read("*all")
f:close()
ngx.print(content)
';
【讨论】:
ngx.exec 来服务文件会更有效。
如果有人需要知道如何从文件中输出最后 n 行:
location /service-man/log {
default_type 'text/plain';
content_by_lua '
local log_path = "/path/to/log.log"
-- Opens a file in read
file = io.open(log_path, "r")
if file==nil
then
ngx.say(log_path .. " can\'t read or does not exists")
return
end
-- sets the default input file
io.input(file)
local lines = {}
-- read the lines in table lines
for line in io.lines() do
table.insert(lines, line)
end
io.close(file)
log_limit = 10
if #lines < log_limit then
log_start = 0
else
log_len = #lines
log_start = log_len - log_limit
end
local one_line = ""
for i, line in ipairs(lines) do
if i > log_start then
one_line = one_line .. line .. "\\n"
end
end
ngx.say(one_line)
';
}
应该兼容 nginx/1.6.2 和 Lua 5.3。
如果您知道如何以更优化的方式制作它,请分享。
【讨论】: