Nginx 默认编译包含但不启用 ngx_http_autoindex_module 模块;只需在 location 块中配置 autoindex on 并确保无 index 文件冲突、权限正确即可启用目录浏览,仅当 nginx -V 无 with-http_autoindex_module 输出时才需重新编译。

Nginx 默认编译时已包含 ngx_http_autoindex_module 模块,但它是**不启用**的。要使用 autoindex on 指令实现目录浏览功能,无需重新编译——只需在配置文件中正确开启并确保模块未被禁用即可。
确认 AutoIndex 模块是否可用
运行以下命令检查当前 Nginx 是否内置了 autoindex 模块:
nginx -V 2>&1 | grep -o with-http_autoindex_module
如果输出含 with-http_autoindex_module,说明模块已编译进二进制,可直接配置使用;若无输出,才需重新编译。
无需编译的常规启用方式(推荐)
绝大多数官方源码包和主流发行版预编译包都默认启用了该模块。只需在 location 块中添加配置:
- 设置
root或alias指向真实目录路径 - 开启
autoindex on; - 可选:用
autoindex_exact_size off;显示易读文件大小,autoindex_format html;(默认)或json/xml
示例配置:
location /files/ {
alias /var/www/files/;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
确实需要重新编译的情况及操作
仅当 nginx -V 输出中完全缺失 with-http_autoindex_module 时才需重编译。步骤如下:
- 进入 Nginx 源码目录,执行
./configure时显式添加:--with-http_autoindex_module(该选项默认开启,但显式写上更稳妥) - 如之前编译时用了
--without-http_autoindex_module,务必删掉该参数 - 执行
make && sudo make install - 验证:
nginx -V 2>&1 | grep autoindex应有输出
常见问题提醒
即使模块存在且配置正确,也可能无法显示目录列表:
-
目录下存在 index 文件(如
index.html),Nginx 会优先返回它而非列表——可删掉或改名,或设index "";禁用索引文件 -
权限不足:Nginx 工作进程(如
www-data或nginx用户)需对目标目录有rx权限 -
root/alias 路径错误:注意
alias末尾斜杠与location匹配的关系,避免路径拼接出错


















