插件窝 干货文章 Nginx目录浏览配置,实现文件列表展示

Nginx目录浏览配置,实现文件列表展示

autoindex Nginx 配置 location 184    来源:    2025-04-16

Nginx目录浏览配置指南

Nginx可以通过简单的配置实现目录浏览功能,允许用户通过浏览器查看服务器上的文件列表。以下是详细配置方法:

基本配置

  1. 打开Nginx配置文件(通常位于/etc/nginx/nginx.conf/etc/nginx/sites-available/下的站点配置文件)

  2. 在需要启用目录浏览的location块中添加以下配置:

location /downloads/ {
    autoindex on;  # 启用目录列表
    autoindex_exact_size off;  # 显示文件大小(KB/MB/GB),而不是字节
    autoindex_localtime on;  # 使用本地时间显示文件修改时间

    # 可选:设置目录列表的字符编码
    charset utf-8;
}

高级配置选项

location /shared/ {
    autoindex on;

    # 自定义目录列表样式
    autoindex_format html;

    # 添加自定义页脚
    add_after_body /nginx-autoindex/footer.html;

    # 限制某些文件类型不显示
    location ~* \.(php|conf|sh)$ {
        autoindex off;
    }
}

安全注意事项

  1. 限制访问范围:只对特定目录启用目录浏览
location /public/ {
    autoindex on;
    # 其他配置...
}

location /private/ {
    autoindex off;
    deny all;  # 完全禁止访问
}
  1. 身份验证:可以添加基本认证
location /restricted/ {
    autoindex on;
    auth_basic "Restricted Access";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

完整示例

server {
    listen 80;
    server_name example.com;

    location /files/ {
        root /var/www;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;

        # 限制某些文件不显示
        location ~* \.(log|conf|key)$ {
            deny all;
        }
    }

    # 其他配置...
}

重启Nginx使配置生效

sudo nginx -t  # 测试配置是否正确
sudo systemctl restart nginx  # 重启Nginx服务

自定义样式

如果需要自定义目录列表的外观,可以使用ngx_http_addition_module模块添加自定义CSS:

location /downloads/ {
    autoindex on;
    add_before_body /nginx-autoindex/header.html;
    add_after_body /nginx-autoindex/footer.html;
}

然后在指定路径创建相应的HTML文件来添加自定义样式和布局。

注意:在生产环境中启用目录浏览可能会暴露敏感信息,请谨慎使用并确保只对非敏感目录启用此功能。