插件窝 干货文章 nginx如何开启列目录

nginx如何开启列目录

autoindex 目录 Nginx 列表 394    来源:    2025-04-25

在Nginx中开启目录列表功能

要在Nginx中开启目录列表功能(即当访问没有index文件的目录时显示文件列表),您需要进行以下配置:

基本配置方法

  1. 打开您的Nginx配置文件(通常在/etc/nginx/nginx.conf/etc/nginx/sites-available/目录下)

  2. 在相应的serverlocation块中添加以下指令:

location /your-directory/ {
    autoindex on;  # 开启目录列表
    autoindex_exact_size off;  # 显示文件大小以易读格式(KB,MB,GB)
    autoindex_localtime on;  # 显示本地时间而非GMT时间
}

完整配置示例

server {
    listen 80;
    server_name example.com;

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

        # 可选:设置目录列表的样式
        # add_before_body /autoindex/header.html;
        # add_after_body /autoindex/footer.html;
    }
}

高级选项

  1. 限制访问:您可能希望限制某些目录的访问
location /private/ {
    autoindex on;
    allow 192.168.1.0/24;
    deny all;
}
  1. 自定义样式:通过自定义HTML文件美化目录列表
location /downloads/ {
    autoindex on;
    autoindex_format html;
    add_before_body /autoindex/header.html;
    add_after_body /autoindex/footer.html;
}
  1. JSON/XML格式:可以输出JSON或XML格式的目录列表
location /api/files/ {
    autoindex on;
    autoindex_format json;  # 也可以是xml
}

注意事项

  1. 修改配置后需要重新加载Nginx使更改生效:

    sudo nginx -t  # 测试配置是否正确
    sudo systemctl reload nginx  # 重新加载配置
    
  2. 出于安全考虑,不建议在生产环境中开放目录列表功能,除非确实需要。

  3. 如果只想对特定目录开启此功能,请确保配置精确匹配该目录路径。

  4. 如果目录列表不显示,请检查Nginx对该目录是否有读取权限。