Ngnix制作下载站11

Ngnix制作下载站

类似于如下效果:

访问: https://nginx.org/download/

image-20220607155607509

nginx使用模块ngx_http_autoindex_module实现, 该模块处理以斜杆/结尾的请求, 并生成目录列表

该模块自动加载, 但默认关闭, 需要使用指令开启配置

指令解析

autoindex指令

启用或禁用目录列表输出

1
2
3
4
5
6
语法: 
autoindex on|off
默认值:
off
位置:
http server location块

autoindex_format指令

设置目录列表的格式

1
2
3
4
5
6
语法:
autoindex_format html|xml|json|jsonp
默认值:
html
位置:
http serve location

autoindex_exact_size指令

对应autoindex_format的HTML格式. 指定是否在目录列表中展示文件详细大小. 默认on, 显示文件确切大小, 单位为bytes. off时, 显示大概大小, 单位KB/MB/GB

1
2
3
4
5
6
语法:
autoindex_exact_size on|off
默认值:
autoindex_exact_size on
位置:
http server location块

autoindex_localtime指令

对应autoindex_format的HTML格式. 是否在目录列表上显示时间. 默认为off, 显示的文件时间为UTC时间. on时, 显示文件的本地时区时间

1
2
3
4
5
6
语法:
autoindex_localtime on|off
默认值:
autoindex_localtime off
位置:
http server location块

配置nginx.conf文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
http{
...
server{
...
# 下载站点配置
location /download{
root /var/www/nginx-module;
autoindex on;
autoindex_exact_size on;
autoindex_format html;
autoindex_localtime on;
}
}
}

效果展示

image-20220607170033885

资源下载用户认证

Nginx通过ngx_http_auth_basic_module模块实现用户认证, 允许通过使用HTTP基本身份验证协议验证用户名和密码来限制对资源的访问, Nginx默认安装了该模块

模块指令

auth_basic指令

使用HTTP基本认证协议开启/关闭用户名密码验证

1
2
3
4
5
6
语法:
auth_basic string|off
默认值:
autoindex_exact_size off
位置:
http server location limit_except块

开启后, 指定字符串会以头信息字段的方式返回到客户端, 给用户提示信息, 但不同浏览器展示方式不同

auth_basic_user_file指令

指定用户名密码验证文件(一般使用htpasswd生成)

1
2
3
4
语法:
auth_basic_user_file file
位置:
http server location limit_except块

指定文件路径, 该文件中包含用户名和密码, 密码需要加密, 可以采用htpasswd自动生成

认证功能实现

修改nginx.conf文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
http{
...
server{
...
# 下载站点配置
location /download{
root /var/www/nginx-module;
autoindex on;
autoindex_exact_size on;
autoindex_format html;
autoindex_localtime on;
auth_basic 'please varify yourself';
auth_basic_user_file /etc/nginx/htpasswd;
}
}
}

安装htpasswd工具

1
sudo apt install httpd-tools

htpasswd指令

1
$ htpasswd -c /etc/nginx/htpasswd user_name	# 创建一个新密码文件

image-20220607175919503

1
$ htpasswd -b /etc/nginx/htpasswd user_name password # 添加新用户

image-20220607180155361

1
$ htpasswd -D /etc/nginx/htpasswd ni8ne # 删除用户

image-20220607180246736

1
$ htpasswd -v /etc/nginx/htpasswd ni9ne	# 验证用户密码

image-20220607180413193

访问资源下载站点

1
http://192.168.253.134/download/

image-20220607180755952