一、概述
本文介绍如何为Nginx服务器配置HTTP基本认证(Basic Authentication),以保护Web应用访问。配置包括密码文件生成、Nginx配置修改、认证缓存管理等内容。
二、密码创建
2.1 安装 Apache 工具(用于生成密码文件)
cmd
# Ubuntu/Debian
sudo apt-get install apache2-utils
# CentOS/RHEL
sudo yum install httpd-tools
2.2 创建用户密码
java
sudo htpasswd -c /etc/nginx/.htpasswd username
- -c 表示创建新文件(如果文件已存在,会覆盖)。
- /etc/nginx/.htpasswd 是密码文件的路径(可自定义)。
- username 是你要设置的账号名。
2.3 追加用户密码
bash
htpasswd -b nginx-config/.htpasswd username pwd
三、Nginx配置修改
3.1 基本认证配置
在Nginx配置文件的server或location块中添加以下指令:
cmd
# 启用基本认证,设置认证提示信息
auth_basic "Authentication Required";
# 指定密码文件路径
auth_basic_user_file /path/to/.htpasswd;
3.2 Docker容器部署配置
在Docker Compose配置中添加密码文件挂载:
cmd
services:
nginx:
image: nginx:latest
container_name: nginx-server
ports:
- '8080:80'
volumes:
# 挂载密码文件
- ./nginx-config/.htpasswd:/etc/nginx/.htpasswd:ro
四、认证缓存机制
浏览器缓存行为,当用户首次成功认证后,浏览器会缓存认证凭据,并在后续请求中自动添加Authorization头:
Authorization: Basic base64(username:password)