Nginx官方版本不支持autoindex_format指令,无法原生输出JSON/XML目录列表;需借助第三方模块(如nginx_autoindex_module)、OpenResty的Lua脚本或后端服务实现结构化输出,同时须注意安全限制与配置细节。

Nginx 本身不支持 autoindex_format 指令,也**不原生提供 JSON 或 XML 格式的目录列表输出**。所谓 autoindex_format 是常见误解,实际是某些第三方模块(如 nginx_autoindex_module)或自定义编译版 Nginx 才具备的扩展功能,标准 Nginx 官方版本中并不存在该指令。
确认你用的是支持 autoindex_format 的增强版 Nginx
标准 Nginx 的 autoindex on 只能生成固定格式的 HTML 列表,无法输出 JSON/XML。若需结构化目录数据,必须满足以下任一条件:
- 已安装并启用第三方模块(如
nginx_autoindex_module),且在编译时启用了--add-module=... - 使用 OpenResty(内置 Lua)自行构造响应体
- 借助后端服务(如 Python/Node.js)代理请求并生成结构化目录
使用 nginx_autoindex_module 输出 JSON
该模块扩展了 autoindex_format 指令,支持 json 和 xml 值。配置示例如下:
location /files/ {
autoindex on;
autoindex_format json; # 关键:启用 JSON 输出
autoindex_exact_size off;
autoindex_localtime on;
}
访问 /files/ 将返回类似:
[
{"name":"..","type":"dir","mtime":"2024-01-01T12:00:00+00:00","size":0},
{"name":"document.pdf","type":"file","mtime":"2024-05-20T09:30:15+00:00","size":204800}
]
注意:autoindex_format json 仅在模块启用且请求头无 Accept: text/html 时生效;部分版本默认仍返回 HTML,需配合 autoindex_ignore_accept_header on 强制启用。
Node.js 可靠编程技能。避免事件循环阻塞、异步陷阱、ESM 兼容问题和内存泄漏。触发词:Node.js 开发、async/await、流处理、性能优化、安全编码。
替代方案:用 Lua + ngx.dir.read 实现灵活输出(OpenResty)
更可控、无需额外模块的方式是使用 OpenResty 的 Lua 脚本遍历目录并构造响应:
location /api/list/ {
content_by_lua_block {
local cjson = require "cjson"
local dir = "/var/www/files/"
local files = {}
local dh = ngx.dir.open(dir)
if not dh then
ngx.status = 500
ngx.say('{"error":"cannot open directory"}')
return
end
local f
while true do
f = dh:read()
if not f then break end
if f ~= "." and f ~= ".." then
local st = ngx.stat(dir .. f)
table.insert(files, {
name = f,
type = st.type == "directory" and "dir" or "file",
size = st.size or 0,
mtime = os.date("!*t", st.mtim)
})
end
end
dh:close()
ngx.header.content_type = "application/json"
ngx.say(cjson.encode(files))
}
}
此方式可自由定制字段、过滤规则、权限控制,且兼容标准 OpenResty 部署。
安全与实用提醒
开放目录列表存在风险,务必注意:
- 避免暴露敏感路径(如
/etc/、/var/log/) - 对
/files/类路径启用访问控制(allow/deny或 auth_basic) - JSON/XML 接口建议加 CORS 头(若前端调用):
add_header 'Access-Control-Allow-Origin' '*'; - 大目录下避免阻塞式遍历,可考虑缓存或异步扫描










