开启目录浏览
Nginx
默认是不允许列出整个目录的,如需此功能,需要使用到 ngx_http_autoindex_module
,接下来进行详细的介绍
autoindex_module配置
autoindex
Syntax: autoindex on | off;
Default:
autoindex off;
Context: http, server, location
启用或禁用目录列表输出。
autoindex_exact_size
Syntax: autoindex_exact_size on | off;
Default:
autoindex_exact_size on;
Context: http, server, location
是否显示文件确切大小,若开启则会以字节大小显示,否则单位是 KB \ MB \ GB
autoindex_localtime
指定输出目录列表中的时间是本地时间还是UTC时间。
Syntax: autoindex_localtime on | off;
Default:
autoindex_localtime off;
Context: http, server, location
官方文档
http://nginx.org/en/docs/http/ngx_http_autoindex_module.html
修改nginx配置
参考如下配置,访问 http://ip:80 端口时会默认以目录浏览形式打开根目录下的内容
server {
listen 80;
root /;
autoindex on;
autoindex_localtime on;
autoindex_exact_size off;
}
访问效果
设置访问验证
当我们上述开启了目录浏览后,任何人都可通过80端口直接访问我们的文件目录并进行下载,所以可以通过 ngx_http_auth_basic_module
简单的对用户信息进行验证。
auth_basic_module 配置
auth_basic
Syntax: auth_basic string | off;
Default:
auth_basic off;
Context: http, server, location, limit_except
开启 auth_basic
会使用 HTTP Basic Authentication
协议对用户名密码进行校验,并会将string参数提示给用户
auth_basic_user_file
Syntax: auth_basic_user_file file;
Default: —
Context: http, server, location, limit_except
指定一个使用如下格式来保存用户名密码的文件,
# comment
name1:password1
name2:password2:comment
name3:password3
官方文档
http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html
生成用户名密码
提供一个在线工具:http://tool.oschina.net/htpasswd 在这里输入用户名密码后选择Crypt加密算法。
修改nginx配置
在虚拟主机配置文件目录下新建一个htpasswd
文件(比如/opt/csmp/conf/htpasswd
),然后编辑htpasswd
文件将刚才的生成结果复制进去。再参考如下配置对nginx
配置进行修改后reload
即可
server {
listen 80;
root /;
autoindex on;
autoindex_localtime on;
autoindex_exact_size off;
auth_basic "Authorized users only";
auth_basic_user_file /opt/csmp/conf/htpasswd;
}