Nginx目录索引(ngx_http_autoindex_module模块)
ngx_http_autoindex_module 模块处理以斜杠字符(’/’)结尾的请求,以html/xml/json/jsonp等格式返回 root/alias 中指向目录的目录结构并生成目录列表。
当 ngx_http_index_module 模块(即server块中对应url的默认返回页面,一般为index.html)找不到索引文件时,通常会将请求传递给 ngx_http_autoindex_module 模块。
ngx_http_index_module 默认编译进Nginx ;--without-http_autoindex_module 取消
用法:
Nginx默认是不允许列出整个目录列表。
Syntax: autoindex on | off;
Default: autoindex off;
Context: http, server, location
# autoindex 常用参数
autoindex_exact_size off;
默认为on, 显示出文件的确切大小,单位是bytes。
修改为off,显示出文件的大概大小,单位是kB或者MB或者GB。
autoindex_localtime on;
默认为off,显示的文件时间为GMT时间。
修改为on, 显示的文件时间为文件的服务器时间。
charset utf-8,gbk;
默认中文目录乱码,添加上解决乱码。
配置示例
编辑配置文件
[root@nginx ~]# vim /etc/nginx/conf.d/autoindex.conf
server {
listen 80;
server_name www.autoindex.com;
location / {
root /myweb;
index index.html;
}
location /download {
autoindex on; # 列出整个目录列表
alias /autoindex_module/; # 服务器路径;或者写 root /autoindex_module/download ,如果这么写就要将所有文件放在服务器的 /autoindex_module/download 目录下
autoindex_localtime on; # 显示的文件时间为文件的服务器时间
charset utf-8,gbk; # 解决中文乱码
autoindex_exact_size off; # 以kB或者MB或者GB单位显示出文件的大小,而不是字节
}
}
location块中 root 和 alias 区别:
nginx指定文件路径有两种方式root和alias。root与alias主要区别在于nginx如何解释location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上。
[root]
语法: root path
配置段: http、server、location、if
说明: 将location中的url添加到root指令对应的路径后面,即可得到最终的服务器路径;即root指令会将location块的”url路径”带入到”root指令路径”中,将带入后的路径作为”最终路径”,使用”最终路径”与url建立对应关系。
以上例子中当用户输入www.autoindex.com时,返回的服务器路径为/myweb/index.html
[alias]
语法: alias path
配置段: location
说明: alias会把location后面url丢弃掉,再将剩余url添加到alias指令对应的路径后面;alias指令则直接将location块的”url路径”与”alias指令路径”建立对应关系。
以上例子中当用户输入www.autoindex.com/download时,返回的服务器路径为/autoindex_module/
- 使用alias时,目录名后面一定要加"/"。
- alias在使用正则匹配时,必须捕捉要匹配的内容并在指定的内容处使用。
- alias只能位于location块中。(root可以不放在location中)创建被索引的文件
[root@nginx ~]# mkdir -p /autoindex_module/{centos,ubuntu,kali}{5..7}
[root@nginx ~]# dd if=/dev/zero of=/autoindex_module/电影.mp4 bs=100M count=10
10+0 records in
10+0 records out
1048576000 bytes (1.0 GB) copied, 5.39017 s, 195 MB/s
[root@nginx ~]# touch /autoindex_module/README.txt
[root@nginx ~]# tree /autoindex_module/
/autoindex_module/
├── centos5
├── centos6
├── centos7
├── kali5
├── kali6
├── kali7
├── README.txt
├── ubuntu5
├── ubuntu6
├── ubuntu7
└── 电影.mp4
9 directories, 2 files
[root@nginx ~]# ls /myweb/
css.css images index.html
[root@nginx ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重载nginx服务
[root@nginx ~]# systemctl reload nginx
[root@nginx ~]# ifconfig ens32 | awk 'NR==2 {print $2}'
192.168.126.41
配置域名解析
效果