在Nginx服务器中配置自动索引目录功能可以让用户浏览服务器上的文件列表。以下是详细的配置方法:
启用autoindex模块(默认已编译进Nginx)
在server或location块中添加以下指令:
location /downloads/ {
autoindex on; # 开启目录列表功能
autoindex_exact_size off; # 显示文件大小(KB/MB/GB),而不是字节
autoindex_localtime on; # 显示本地时间而非GMT时间
autoindex_format html; # 默认格式,也可以是json/xml/jsonp
}
server {
listen 80;
server_name example.com;
# 根目录配置
root /var/www/files;
location / {
# 禁止上级目录访问
deny all;
}
location /public/ {
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
# 可选:添加自定义样式
add_before_body /autoindex/header.html;
add_after_body /autoindex/footer.html;
# 限制访问权限(可选)
allow 192.168.1.0/24;
deny all;
}
}
自定义索引页面样式:
location /downloads/ {
autoindex on;
# 自定义CSS样式
add_header Content-Style-Type "text/css";
add_header Content-Security-Policy "style-src 'self' 'unsafe-inline'";
}
JSON格式输出:
location /api/files/ {
autoindex on;
autoindex_format json;
}
限制文件类型显示:
location /images/ {
autoindex on;
# 只显示jpg和png文件
autoindex_filter "*.jpg" "*.png";
}
限制敏感目录访问:
location ~ /\.(git|svn|ht) {
deny all;
}
禁用PHP等脚本执行:
location ~ \.php$ {
deny all;
}
添加认证:
location /secure/ {
autoindex on;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
配置完成后,测试并重启Nginx:
sudo nginx -t # 测试配置
sudo systemctl restart nginx # 重启服务
这样配置后,访问对应的URL路径就能看到文件目录列表了。