插件窝 干货文章 Nginx服务器下如何配置使用索引目录

Nginx服务器下如何配置使用索引目录

autoindex Nginx location 配置 441    来源:    2025-04-23

Nginx服务器配置索引目录指南

在Nginx服务器中配置自动索引目录功能可以让用户浏览服务器上的文件列表。以下是详细的配置方法:

基本配置方法

  1. 启用autoindex模块(默认已编译进Nginx)

  2. 在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;
    }
}

高级配置选项

  1. 自定义索引页面样式

    location /downloads/ {
       autoindex on;
       # 自定义CSS样式
       add_header Content-Style-Type "text/css";
       add_header Content-Security-Policy "style-src 'self' 'unsafe-inline'";
    }
    
  2. JSON格式输出

    location /api/files/ {
       autoindex on;
       autoindex_format json;
    }
    
  3. 限制文件类型显示

    location /images/ {
       autoindex on;
       # 只显示jpg和png文件
       autoindex_filter "*.jpg" "*.png";
    }
    

安全注意事项

  1. 限制敏感目录访问

    location ~ /\.(git|svn|ht) {
       deny all;
    }
    
  2. 禁用PHP等脚本执行

    location ~ \.php$ {
       deny all;
    }
    
  3. 添加认证

    location /secure/ {
       autoindex on;
       auth_basic "Restricted";
       auth_basic_user_file /etc/nginx/.htpasswd;
    }
    

重启Nginx生效

配置完成后,测试并重启Nginx:

sudo nginx -t  # 测试配置
sudo systemctl restart nginx  # 重启服务

这样配置后,访问对应的URL路径就能看到文件目录列表了。