Nginx基础认证:保护Web资源的简单方案
Nginx认证方案实施指南
1. Nginx核心功能概述
1.1 反向代理
- 请求分发到内部服务
- 隐藏内部服务架构
- 提供统一访问入口
1.2 负载均衡
常用算法:
- Round Robin (rr):轮询分配
- Weight:权重分配
- IP Hash:基于IP的会话保持
- Fair:按响应时间分配
- URL Hash:基于URL的分配
1.3 Web服务器功能
- 静态资源服务
- HTTP/HTTPS代理
- WebSocket代理
- 安全防护
1.4 正向代理
- 位于客户端和源服务器之间
- 代表客户端访问外部资源
- 提供访问控制和缓存功能
2. HTTP Basic认证实现
2.1 安装工具
# 安装htpasswd工具
yum install httpd-tools -y
2.2 创建用户
# 创建新的密码文件并添加用户
htpasswd -bc /etc/nginx/passwd/auth_file admin 123456admin
# 添加额外用户(不使用-c参数)
htpasswd -b /etc/nginx/passwd/auth_file user2 password2
2.3 Nginx配置
server {
listen 8081;
server_name es.server.com;
# 保护所有路径
location ~* / {
# 设置认证提示
auth_basic "Protected Resource";
# 指定密码文件
auth_basic_user_file /etc/nginx/passwd/auth_file;
# 禁用目录浏览
autoindex off;
# 反向代理设置
proxy_pass http://127.0.0.1:9200;
# 代理头部设置
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# 超时设置
proxy_connect_timeout 60;
proxy_send_timeout 60;
proxy_read_timeout 60;
}
}
3. 安全最佳实践
3.1 密码管理
- 使用强密码策略
- 定期更新密码
- 避免共享账号
- 记录认证日志
3.2 访问控制
# 限制特定IP访问
location /admin {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/passwd/auth_file;
allow 192.168.1.0/24;
deny all;
}
# 结合SSL/TLS
server {
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
auth_basic "Secure Area";
auth_basic_user_file /etc/nginx/passwd/auth_file;
}
}
3.3 性能优化
# 缓存认证结果
auth_basic_user_file /etc/nginx/passwd/auth_file;
proxy_cache_path /tmp/cache keys_zone=auth_cache:10m;
location / {
proxy_cache auth_cache;
proxy_cache_key $remote_user;
proxy_cache_valid 200 10m;
}
4. 常见应用场景
4.1 开发环境保护
# 开发环境配置
server {
listen 80;
server_name dev.example.com;
location / {
auth_basic "Development Environment";
auth_basic_user_file /etc/nginx/passwd/dev_auth;
proxy_pass http://dev_backend;
}
}
4.2 管理界面保护
# 管理后台配置
location /admin {
auth_basic "Admin Panel";
auth_basic_user_file /etc/nginx/passwd/admin_auth;
proxy_pass http://admin_backend;
}
4.3 API访问控制
# API保护配置
location /api {
auth_basic "API Access";
auth_basic_user_file /etc/nginx/passwd/api_auth;
proxy_pass http://api_backend;
}
5. 故障排查
5.1 常见问题
-
认证失败
- 检查密码文件权限
- 验证用户名密码正确性
- 检查文件路径配置
-
性能问题
- 监控认证延迟
- 优化缓存配置
- 调整超时设置
5.2 调试技巧
# 测试认证
curl -v -u username:password http://your-server
# 查看错误日志
tail -f /var/log/nginx/error.log
# 验证配置
nginx -t
6. 监控和维护
6.1 日志配置
# 启用访问日志
access_log /var/log/nginx/auth.log combined;
# 自定义日志格式
log_format auth '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
6.2 定期维护
- 密码更新流程
- 日志轮转配置
- 性能监控设置
- 安全审计检查
7. 注意
7.1 nginx反向代理的域名问题
proxy_pass http://api_backend;
这个域名必须是可访问的,不然nginx启动探测的时候会报错,导致服务启动失败