前面搭建了一个 Nginx 文件服务器,只是简单的展示了一下目录。现通过 autoindex 页面功能的配置来达到美化 nginx 目录的效果(参考网上教程)。autoindex on 配置展示 nginx 目录的默认版比较简单,样式也不太好看。新版有 github 风格,当然还有些差距。主要改进点如下:

  • 使用 nginx 的 autoindex 页脚(footer) 功能添加 javascript 来重新渲染并美化页面。
  • 使用 twitter bootstrap 和 github octicons 做素材, 并适配移动端。
  • 检测当前页面 Readme.md 并渲染,和 github 保持一致。

改进方案

  1. 下载 autoindex.html 文件到 ftp 服务器根目录
  2. 在 autoindex 指令下添加 add_after_body /autoindex.html,并重启 nginx。

autoindex.html 文件下载地址:https://phuslu.github.io/autoindex.html

完整的 autoindex 指令如以下形式(虚拟主机配置不同,root 和 location 后跟的参数也不一样):

    location / {
        root /wwwroot/ftp/;
        index index.html index.htm index.php;
        autoindex on; # 显示目录(默认off)
        autoindex_format html;
        autoindex_exact_size off; # 显示精确文件大小
        autoindex_localtime on; # 显示本地文件时间
        add_after_body /autoindex.html;
    }

unknown directive "add_after_body" 问题解决

在重启 nginx 的过程中,可能会报以下错误:

Stoping nginx... nginx: [emerg] unknown directive "add_after_body" in /usr/local/nginx/conf/vhost/domain.com.conf:23
 failed. Use force-quit

add_after_body 指令不认识,这一般是由于 Nginx 编译时未将 ngx_http_addition_module 模块添加进去。add_after_body 指令被定义在 ngx_http_addition_module 模块中,具体点击查看文档。所以 Nginx 需要重新编译,并在编译时添加 --with-http_addition_module 参数。

我编译 Nginx 的参数如下:

./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-stream --with-http_gzip_static_module --with-http_sub_module --with-http_addition_module

因为之前版本就是编译而来的,所以不需要再安装依赖。否则,可能报错:openssl 已安装,nginx 编译仍报错: SSL modules require the OpenSSL library.

隐藏 autoindex.html 文件

autoindex.html 会被自动添加到 Nginx 自动生成的目录页面中,进行渲染生效,但这个文件本身并不属于 ftp 服务器上传内容。如果不喜欢这个多余的文件,想把 autoindex.html 文件隐藏掉,还是有办法的。

这个办法主要借助的就是 Linux 系统默认不展示 . 开头的文件这一特性。常见的有 ....git 之类的,这些文件或者文件夹本身系统默认隐藏的。... 表示当前目录,和上级目录,不适合隐藏,可以自建一个 .git 文件夹(文件夹名字可以随便取),然后把 autoindex.html 文件到目录下面,最后修改配置为 add_after_body /.git/autoindex.html,再次重启 Nginx 即可。

文章目录