【问题标题】:Nginx + LUA, how to output file?Nginx + LUA,如何输出文件?
【发布时间】:2016-07-26 04:49:50
【问题描述】:

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

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

【问题讨论】:

    标签: nginx lua


    【解决方案1】:

    好的,找到了

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

    【讨论】:

    • 让 nginx 使用内部位置和ngx.exec 来服务文件会更有效。
    • @chanux 好像你的博客已经死了:(你能在某个地方重新发布这篇文章吗?
    • @scythargon 很抱歉让它死了。我把它放回去了。我搞砸了重定向,但 here is it.
    • @chanux 感谢您的博客,nginx 内部重定向救救我
    • @chanux 感谢发帖,最后一个网址无效,这里是最新的路径chanux.me/blog/post/lua-x-accel-redirect
    【解决方案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。

    如果您知道如何以更优化的方式制作它,请分享。

    【讨论】:

      猜你喜欢
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 2017-01-27
      • 2013-11-20
      • 2021-01-13
      • 1970-01-01
      相关资源
      最近更新 更多