Nginx 可以通过 HTTP Basic Authentication 实现账号密码验证,这是一种简单的认证方式,客户端需要在请求头中携带 Base64 编码的用户名和密码。
首先需要使用 htpasswd
工具创建密码文件:
# 安装htpasswd工具(如果尚未安装)
# 对于Debian/Ubuntu:
sudo apt-get install apache2-utils
# 对于CentOS/RHEL:
sudo yum install httpd-tools
# 创建密码文件(首次创建需加-c参数)
sudo htpasswd -c /etc/nginx/.htpasswd username1
# 添加更多用户(不加-c参数)
sudo htpasswd /etc/nginx/.htpasswd username2
在需要保护的 location 或 server 块中添加以下配置:
server {
listen 80;
server_name example.com;
location /protected/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
}
}
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html;
# 保护整个网站
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# 或者只保护特定路径
location /private/ {
auth_basic "Private Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
# 排除某些路径不需要认证
location /public/ {
auth_basic off;
}
}
# 测试配置是否正确
sudo nginx -t
# 重载配置
sudo systemctl reload nginx
location /admin/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
location /protected/ {
auth_basic "Protected Area";
auth_basic_user_file /etc/nginx/.htpasswd;
location ~* \.(jpg|png|css|js)$ {
auth_basic off;
}
}
bash
sudo chmod 644 /etc/nginx/.htpasswd
sudo chown root:root /etc/nginx/.htpasswd
问题1:认证不生效 - 检查配置是否正确加载 - 确保密码文件路径正确 - 检查密码文件格式是否正确
问题2:密码文件权限问题 - 确保Nginx工作进程有权限读取密码文件 - 检查SELinux/AppArmor是否阻止访问
问题3:认证后仍然无法访问 - 检查是否有其他访问控制规则冲突 - 查看Nginx错误日志获取更多信息