特定场景下跳过content_by_lua_file,让NGINX处理静态文件
实现content_by_lua_file按需执行,未命中时回退静态文件服务
当前NGINX配置:
location /x { access_by_lua_file auth/auth.lua; content_by_lua_file auth/content.lua; }
需求:access_by_lua_file正常运行,无返回时执行content_by_lua_file。希望缓存命中时由content_by_lua_file返回内容,否则跳过该指令,让NGINX直接提供静态文件。
当前content.lua代码:
local files_cache = require 'files_cache' local filePath = ngx.var.file_path local fileContent = files_cache.load(filePath) if fileContent ~= nil then ngx.header["X-Source"] = "Cache" ngx.say(fileContent) ngx.status = ngx.HTTP_OK return ngx.exit(ngx.status) end
问题原因
当前代码在缓存未命中时,脚本执行完毕后会占据NGINX的content阶段执行权,导致NGINX不会自动触发静态文件服务流程。
解决方案
1. 修改content.lua代码
在缓存未命中时,主动转发到专门处理静态文件的命名location:
local files_cache = require 'files_cache' local filePath = ngx.var.file_path local fileContent = files_cache.load(filePath) if fileContent ~= nil then ngx.header["X-Source"] = "Cache" ngx.say(fileContent) ngx.status = ngx.HTTP_OK return ngx.exit(ngx.status) end -- 缓存未命中,转发到静态文件处理location ngx.exec("@static")
2. 更新NGINX配置
新增命名location @static 负责静态文件服务,替换实际的静态文件根目录:
location /x { access_by_lua_file auth/auth.lua; content_by_lua_file auth/content.lua; } location @static { root /your/actual/static/files/path; # 替换为你的静态文件根目录 try_files $uri $uri/ =404; }
这样一来,当缓存命中时,content.lua直接返回缓存内容;未命中时,NGINX会跳转到@static location处理静态文件,和没配置content_by_lua_file的效果一致。
内容的提问来源于stack exchange,提问作者Paflow
相关产品推荐
相关产品推荐

