NGINX和Lua脚本:在content_by_lua中条件使用

我试图创建一个有条件的 content_by_lua 脚本,在此条件下,内容应该仅由 lua 设置。

例如:

nginx.conf

location / {
        content_by_lua_file  /nginx/lua/nginx.lua;

        root   /nginx/www;
        index  index.html;

        location ~* \.(?:ico|css|js|gif|jpe?g|png|woff|ttf)$ {
            expires max;
            add_header Pragma public;
            add_header Cache-Control "public, must-revalidate, proxy-revalidate";
        }
    }

nginx.lua

if condition then
    ngx.header["Content-type"] = "text/html"
    ngx.say('<H1>Hello World.</H1>');
    ngx.exit(0)
else
    -- serve the original content (index.html)
end

问题是-在相同路由下,nginx 中的 lua 脚本不支持 2 个 content 指令,我可以做出解决办法吗?

在当前用法下,当条件为 false 时,我希望显示 index.html,但实际上得到的是空白页面。

点赞
用户1126335
用户1126335

你可以使用 ngx.exec 调用一个内部调用。

nginx.conf

location / {
    content_by_lua_file  /nginx/lua/nginx.lua;

    root   /nginx/www;
    index  index.html;

    location ~* \.(?:ico|css|js|gif|jpe?g|png|woff|ttf)$ {
        expires max;
        add_header Pragma public;
        add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    }
}

location /default_index {
    root   /nginx/www;
    index  index.html;
}

nginx.lua

if condition then
    ngx.header["Content-type"] = "text/html"
    ngx.say('<H1>Hello World.</H1>');
    ngx.exit(0)
else
    -- serve the original content (index.html)
    ngx.exec("/default_index", ngx.var.args)
end
2015-12-18 17:37:01