在Nginx中添加账号密码验证(HTTP基本认证)是一种简单有效的访问控制方法。以下是详细的配置步骤:
首先需要创建一个包含用户名和加密密码的文件:
sudo sh -c "echo -n '用户名:' >> /etc/nginx/.htpasswd"
sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"
系统会提示你输入并确认密码。也可以使用htpasswd
工具(需要安装apache2-utils):
sudo apt-get install apache2-utils # Ubuntu/Debian
sudo yum install httpd-tools # CentOS/RHEL
sudo htpasswd -c /etc/nginx/.htpasswd 用户名
在Nginx配置文件中添加认证配置:
server {
listen 80;
server_name example.com;
location / {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
}
}
sudo nginx -t # 测试配置是否正确
sudo systemctl reload nginx # 重载配置
排除特定路径:
location /public {
auth_basic off;
}
对整个服务器启用认证:
server {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
# ...
}
使用多个密码文件:
auth_basic_user_file /etc/nginx/.htpasswd1;
auth_basic_user_file /etc/nginx/.htpasswd2;
/etc/nginx/conf.d/.htpasswd
)bash
sudo chown root:www-data /etc/nginx/.htpasswd
sudo chmod 640 /etc/nginx/.htpasswd
/var/log/nginx/error.log
location
块中配置了认证这样配置后,访问你的网站时就会弹出登录对话框要求输入用户名和密码了。