要在Nginx中配置目录列表显示并使用密码保护访问权限,您需要进行以下配置:
首先启用目录列表功能,在Nginx配置文件中添加或修改以下内容:
server {
listen 80;
server_name yourdomain.com;
location /downloads/ {
autoindex on; # 启用目录列表
autoindex_exact_size off; # 显示文件大小(KB/MB)
autoindex_localtime on; # 使用本地时间而非GMT
# 可选:自定义目录列表样式
autoindex_format html;
# 密码认证配置
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}
使用htpasswd
工具创建密码文件:
sudo apt-get install apache2-utils # 如果尚未安装
sudo htpasswd -c /etc/nginx/.htpasswd username
系统会提示您输入并确认密码。如果要添加更多用户,去掉-c
选项(-c
表示创建新文件):
sudo htpasswd /etc/nginx/.htpasswd anotheruser
确保Nginx可以读取密码文件:
sudo chown www-data:www-data /etc/nginx/.htpasswd
sudo chmod 640 /etc/nginx/.htpasswd
sudo nginx -t # 测试配置是否正确
sudo systemctl reload nginx
location /downloads/ {
autoindex on;
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
# 允许特定IP无密码访问
satisfy any;
allow 192.168.1.100;
deny all;
}
location /downloads/ {
autoindex on;
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
# 自定义目录列表头部和底部
autoindex_format html;
add_before_body /nginx/autoindex/header.html;
add_after_body /nginx/autoindex/footer.html;
}
location ~* \.(php|log|conf)$ {
deny all;
}
完成以上配置后,访问您配置的目录时,系统会要求输入用户名和密码,验证通过后才能查看目录内容。