Nginx可以通过简单的配置实现目录浏览功能,允许用户通过浏览器查看服务器上的文件列表。以下是详细配置方法:
打开Nginx配置文件(通常位于/etc/nginx/nginx.conf
或/etc/nginx/sites-available/
下的站点配置文件)
在需要启用目录浏览的location
块中添加以下配置:
location /downloads/ {
autoindex on; # 启用目录列表
autoindex_exact_size off; # 显示文件大小(KB/MB/GB),而不是字节
autoindex_localtime on; # 使用本地时间显示文件修改时间
# 可选:设置目录列表的字符编码
charset utf-8;
}
location /shared/ {
autoindex on;
# 自定义目录列表样式
autoindex_format html;
# 添加自定义页脚
add_after_body /nginx-autoindex/footer.html;
# 限制某些文件类型不显示
location ~* \.(php|conf|sh)$ {
autoindex off;
}
}
location /public/ {
autoindex on;
# 其他配置...
}
location /private/ {
autoindex off;
deny all; # 完全禁止访问
}
location /restricted/ {
autoindex on;
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
}
server {
listen 80;
server_name example.com;
location /files/ {
root /var/www;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
# 限制某些文件不显示
location ~* \.(log|conf|key)$ {
deny all;
}
}
# 其他配置...
}
sudo nginx -t # 测试配置是否正确
sudo systemctl restart nginx # 重启Nginx服务
如果需要自定义目录列表的外观,可以使用ngx_http_addition_module
模块添加自定义CSS:
location /downloads/ {
autoindex on;
add_before_body /nginx-autoindex/header.html;
add_after_body /nginx-autoindex/footer.html;
}
然后在指定路径创建相应的HTML文件来添加自定义样式和布局。
注意:在生产环境中启用目录浏览可能会暴露敏感信息,请谨慎使用并确保只对非敏感目录启用此功能。