要在Nginx中设置基本的用户名密码认证,可以通过以下步骤实现:
首先需要创建一个包含用户名和密码的文件:
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站点配置文件(通常在/etc/nginx/sites-available/
目录下):
server {
listen 80;
server_name yourdomain.com;
location / {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
root /var/www/html;
index index.html;
}
}
sudo nginx -t # 测试配置是否正确
sudo systemctl restart nginx # 重启Nginx
location /private/ {
auth_basic "Private Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /public/ {
auth_basic off;
}
location / {
satisfy any;
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
}
确保.htpasswd
文件对Nginx可读但不可公开访问:
sudo chown www-data:www-data /etc/nginx/.htpasswd
sudo chmod 640 /etc/nginx/.htpasswd
对于生产环境,建议结合HTTPS使用,因为基本认证是明文传输凭据的。
如果需要更高级的认证方式,可以考虑集成LDAP、OAuth等方案。
要添加更多用户,使用不带-c
选项的htpasswd
命令:
sudo htpasswd /etc/nginx/.htpasswd 另一个用户名