插件窝 干货文章 怎么启用Nginx目录浏览功能

怎么启用Nginx目录浏览功能

Nginx autoindex 目录 配置 517    来源:    2025-04-25

启用Nginx目录浏览功能

要在Nginx中启用目录浏览功能,您需要修改Nginx配置文件。以下是详细步骤:

基本配置方法

  1. 打开Nginx配置文件(通常是/etc/nginx/nginx.conf/etc/nginx/sites-available/your-site

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

location /path/to/directory {
    autoindex on;  # 启用目录列表
    autoindex_exact_size off;  # 显示文件大小以易读格式(KB,MB,GB)
    autoindex_localtime on;  # 使用本地时间显示文件修改时间
}

完整示例配置

server {
    listen 80;
    server_name example.com;

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

可选参数说明

  • autoindex_format:指定目录列表格式(html/xml/json/jsonp)
  • autoindex_exact_size:on显示精确字节数,off显示易读格式
  • autoindex_localtime:on使用本地时间,off使用UTC时间

安全性考虑

启用目录浏览可能会暴露敏感信息,建议:

  1. 限制特定目录而非整个网站
  2. 结合allow/deny指令限制访问IP
  3. 使用.htaccess或Nginx的auth_basic添加基础认证

测试和重载配置

  1. 测试配置是否正确:
sudo nginx -t
  1. 重载Nginx使配置生效:
sudo systemctl reload nginx

完成以上步骤后,访问配置的目录路径应该就能看到文件列表了。