Nginx + LUA,如何输出文件?

时间:2014-06-26 07:13:06

标签: nginx lua

Nginx + Lua中的文件输出有问题。我选择了LUA,因为nginx逻辑非常复杂,基于引用者或子域等等。

有像/img/am1/s/1.jpg这样的请求我需要检查/somepath/am1/1.jpg中是否存在文件。如果存在,则输出,否则代理请求后端。

2 个答案:

答案 0 :(得分:8)

好的,找到了

content_by_lua '
    local file = "/path..."
    local f = io.open(file, "rb")
    local content = f:read("*all")
    f:close()
    ngx.print(content)
';

答案 1 :(得分:2)

如果有人需要知道如何从文件输出最后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兼容。

如果您知道如何以更优化的方式进行分享,请分享。