baicai

白菜

一个勤奋的代码搬运工!

nginx 启用目录索引,显示文件列表

在 nginx 中,如果特定目录中没有 index.html 文件,则默认会返回 404 Not Found 的错误。

但是,Nginx 自动索引模块 —— ngx_http_autoindex_module 模块,提供了一种自动生成列表的方法,添加自动索引非常容易,使用 autoindex on 即可。下面的配置,将在访问特定请求时返回目录结构。

官方参考: http://nginx.org/en/docs/http/ngx_http_autoindex_module.html
    server {
            listen   80;
            ... ...
            
            location /index_dir {
            autoindex on;
            }
    }

除了简单地使用自动索引打开或关闭之外,还可以对其做其他的配置,包括:

    autoindex_exact_size; 显示输出的确切文件大小,还是最接近的KB,MB或GB。默认为on,显示出文件的确切大小,单位是bytes。改为off后,显示出文件的大概大小,单位是kB或者MB或者GB。
    autoindex_format; 该指令指定Nginx索引列表应以什么格式输出。该指令有4个选项:html/xml/json/jsonp。
    autoindex_localtime; 显示的文件时间为GMT时间。 注意:改为on后,显示的文件时间为文件的服务器时间。

使用这几个配置后配置内容类似于如下内容:

location /index_dir/ {
    root   /data/index_dir/;  
    autoindex on;
    autoindex_exact_size off;
    autoindex_format html;
    autoindex_localtime on;
}

如果有中文目录的话会出现乱码问题,所以还需要在下面添加这一句:

charset utf-8;

charset utf-8,gbk;
加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。