很多人可能没有用过 nginx 的 autoindex 功能。但是,我相信大家都用过一些网站的目录浏览功能。哎,为什么有的 Nginx 能使网站按照网页的形式浏览,而有的网站则显示的是按照目录浏览?这是为什么?今天我们一起来学习学习 nginx 中的 autoindex 指令。
autoindex 指令的默认值是 off,它存在于 ngx_http_autoindex_module 模块中。如果我们设置为 on,则代表我们将以目录的形式展现给用户。autoindex 指令可以配置在 http 指令块或 location 指令块中。
location /down/ {
autoindex on;
}

另外 Nginx 的目录浏览还有几个比较有用的参数,可以根据自己的需求添加:
- autoindex_exact_size off; 默认为 on,显示出文件的确切大小,单位是 bytes。改为 off 后,显示出文件的大概大小,单位是 kB 或者 MB 或者 GB。
- autoindex_localtime on; 默认为 off,显示的文件时间为 GMT 时间。改为 on 后,显示的文件时间为文件的服务器时间。
- autoindex_format html; 默认为 html。以网页的风格展示目录内容。该属性在1.7.9及以上适用。

autoindex 中文乱码问题
群里有很多人反映使用 autoindex 指令,遇到中文会产生乱码。解决这个问题我们只需要配置:charset utf-8,gbk; 指令即可。
location /download {
root /home/map/www/; #指定目录所在路径
autoindex on; #开启目录浏览
autoindex_format html; #以html风格将目录展示在浏览器中
autoindex_exact_size off; #切换为 off 后,以可读的方式显示文件大小,单位为 KB、MB 或者 GB
autoindex_localtime on; #以服务器的文件时间作为显示的时间
charset utf-8,gbk; #展示中文文件名
}
autoindex 目录美化
目录美化这个操作稍微麻烦一点。稍微不小心,可能就会出错。按照我的步骤来即可!
首先,下载安装 fancy。

然后,fancy 索引配置。
server {
listen 80;
server_name test.xttblog.com;
access_log /data/logs/nginx/test.ttlsa.com.access.log main;
index index.html index index.html;
root /data/site/xttblog.ttlsa.com;
location / {
}
location ~ ^/2589(/.*){
fancyindex on;
fancyindex_exact_size off;
fancyindex_localtime on;
fancyindex_footer "myfooter.shtml";
}
}
然后重启 Nginx 即可。

运行效果如上所示。

: » nginx autoindex设置目录浏览和乱码问题解决以及autoindex美化
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/252784.html