Nginx autoindex 配置详解
autoindex 是 Nginx 的核心模块功能,用于开启目录列表展示(当访问的 URL 对应服务器上的目录且无默认索引文件时,自动列出目录内文件/子目录)。下面从基础配置到高级优化,一步步教你配置。
一、基础配置(核心参数)
1. 核心指令说明
| 指令 | 作用 |
|---|---|
autoindex on; | 开启目录列表(默认 off) |
autoindex off; | 关闭目录列表(默认值) |
autoindex_exact_size on; | 显示文件精确大小(字节);设为 off 显示易读单位(KB/MB/GB) |
autoindex_localtime on; | 显示文件本地时间;设为 off 显示 GMT 时间(默认) |
2. 最简配置示例
以配置 /data/files 目录的目录列表为例:
server {
listen 80;
server_name file.example.com; # 替换为你的域名/IP
# 根目录指向要展示的文件夹
root /data/files;
location / {
# 核心:开启目录列表
autoindex on;
# 优化:显示易读的文件大小(KB/MB)
autoindex_exact_size off;
# 优化:显示本地时间(而非GMT)
autoindex_localtime on;
# 可选:指定默认索引文件(无该文件时才会显示目录列表)
index index.html index.htm;
}
}
二、进阶配置(权限/安全/美化)
1. 限制访问(仅允许指定 IP)
如果不想公开目录列表,可增加 IP 白名单:
server {
listen 80;
server_name file.example.com;
root /data/files;
location / {
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
index index.html;
# 仅允许 192.168.1.100 和 10.0.0.0/24 网段访问
allow 192.168.1.100;
allow 10.0.0.0/24;
deny all;
}
}
2. 带密码验证的目录列表
先通过 htpasswd 创建密码文件,再配置 Nginx 验证:
# 安装 htpasswd(Debian/Ubuntu)
apt install apache2-utils
# 或(CentOS/RHEL)
yum install httpd-tools
# 创建密码文件(存储路径建议非网站根目录)
htpasswd -c /etc/nginx/conf.d/htpasswd admin # 设置用户名 admin,按提示输入密码
Nginx 配置:
server {
listen 80;
server_name file.example.com;
root /data/files;
location / {
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
# 密码验证
auth_basic "请输入账号密码"; # 验证提示语
auth_basic_user_file /etc/nginx/conf.d/htpasswd; # 密码文件路径
}
}
3. 仅对特定目录开启 autoindex
比如只展示 /data/files/download 目录,其他目录不展示:
server {
listen 80;
server_name file.example.com;
root /data/files;
# 全局关闭
autoindex off;
# 仅 /download 目录开启
location /download/ {
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
}
三、配置生效步骤
- 检查配置语法是否错误:
nginx -t - 重载 Nginx 配置(无需重启,不中断服务):
nginx -s reload
四、常见问题排查
-
配置后仍不显示目录列表:
- 确认目录存在且 Nginx 进程有读取权限(比如
chmod 755 /data/files); - 确认目录下无
index.html/index.htm等默认索引文件; - 检查
selinux/防火墙是否拦截(临时关闭 selinux:setenforce 0)。
- 确认目录存在且 Nginx 进程有读取权限(比如
-
中文文件名乱码:
在http/server/location块中添加字符集配置:charset utf-8,gbk;
总结
autoindex on;是开启目录列表的核心,搭配autoindex_exact_size off;和autoindex_localtime on;可优化展示效果;- 生产环境建议添加 IP 白名单或密码验证,避免目录列表公开暴露;
- 配置后需通过
nginx -t检查语法,再nginx -s reload重载生效。