1、简介

Nginx的目录列表功能默认是关闭的,如果需要打开Nginx的目录列表功能,需要手动配置,还可以进行访问验证,nginx通过ngx_http_autoindex_module模块实现。

2、配置目录浏览

server {
   listen 80;
   server_name www.herlly.cn;            //访问http://ip,发现访问的站点目录还是默认的;可以将此处的localhost直接改成服务器ip地址
   root /var/www/html;
   index index.html;
 
   location / {
   autoindex on;
   autoindex_exact_size off;
   autoindex_localtime on;
   }
 
   location /images {
      root   /var/www/html/herlly;
      autoindex on;
        }
 
   location /img   {
      autoindex  on;                        # 自动显示目录,必须打开
      autoindex_exact_size  off;            # 改为off后,显示出文件的大概大小,单位是kB或者MB或者GB;即人性化方式显示文件大小否则以byte显示
      autoindex_localtime on;               # 显示的文件时间为文件的服务器时间;即按服务器时间显示
      limit_rate_after 10m;                 # 10m之后下载速度为10k
      limit_rate 10k;
      alias /opt/html/herlly;   # 虚拟目录
      }
 
}

# 重新加载配置
nginx -s reload

# 访问
http://localhost/

3、设置访问验证

# 安装工具
yum install -y *htpasswd

# 创建用户/密码
htpasswd -c/usr/local/nginx/conf/auth_password herlly # 会提示输入两次密码
cat /usr/local/nginx/conf/auth_password

# 修改nginx配置
location ^~ /soft/ {
     root /var/www/html;             # 此处为soft的上一级目录。注意root和alias虚拟目录设置区别
     autoindex on;
     autoindex_exact_size off;
     autoindex_localtime on;
     auth_basic "MyPathAuthorized";  # 为提示信息,可以自行修改;会出现在第一次访问Nginx站点的弹出框内
     auth_basic_user_file/usr/local/nginx/conf/auth_password;    # 最好跟htpasswd文件的全路径
}