Nginx默认情况下是不允许列出目录内容的,但可以通过简单的配置开启这一功能。以下是详细的配置方法和分析:
location /downloads/ {
autoindex on; # 开启目录列表
autoindex_exact_size off; # 以易读方式显示文件大小(KB,MB,GB)
autoindex_localtime on; # 显示本地时间而非GMT时间
autoindex_format html; # 以HTML格式输出(默认)
}
autoindex on
on
或 off
(默认)autoindex_exact_size
on
(默认):显示精确字节数off
:显示易读格式(KB, MB, GB等)autoindex_localtime
off
(默认):显示GMT时间on
:显示服务器本地时间autoindex_format
html
(默认), xml
, json
, jsonp
location /shared/ {
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
# 添加自定义header
add_header X-Frame-Options SAMEORIGIN;
# 限制某些文件类型不显示
autoindex_ignore "*.txt" "*.md";
# 自定义目录列表样式
add_before_body /autoindex/header.html;
add_after_body /autoindex/footer.html;
}
限制访问范围:建议只在特定目录开启此功能
location /public/ {
autoindex on;
# 其他配置...
}
认证保护:为敏感目录添加基础认证
location /internal/ {
autoindex on;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
IP限制:只允许特定IP访问
location /secure/ {
autoindex on;
allow 192.168.1.0/24;
deny all;
}
403 Forbidden错误
chmod +r /path/to/directory
样式问题
add_before_body
和add_after_body
添加自定义HTML中文文件名乱码
nginx
charset utf-8;
通过以上配置,您可以灵活控制Nginx的目录列表功能,既满足需求又保障安全性。