Nginx提供了基本的HTTP认证功能,可以通过用户名和密码来限制对网站或特定目录的访问。以下是实现步骤:
首先需要创建一个存储用户名和密码的文件。Nginx使用htpasswd
工具来管理这些凭据。
# 安装htpasswd工具(如果尚未安装)
sudo apt-get install apache2-utils # Ubuntu/Debian
sudo yum install httpd-tools # CentOS/RHEL
# 创建密码文件并添加第一个用户
sudo htpasswd -c /etc/nginx/.htpasswd username1
添加更多用户时(不要使用-c
选项,否则会覆盖现有文件):
sudo htpasswd /etc/nginx/.htpasswd username2
在Nginx配置文件中添加认证配置:
server {
listen 80;
server_name example.com;
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
location / {
# 其他配置...
}
}
server {
listen 80;
server_name example.com;
location / {
# 公共访问区域
}
location /private/ {
auth_basic "Private Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
}
}
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 / {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
location /public/ {
auth_basic off;
}
}
location /area1/ {
auth_basic "Area One";
auth_basic_user_file /etc/nginx/.htpasswd.area1;
}
location /area2/ {
auth_basic "Area Two";
auth_basic_user_file /etc/nginx/.htpasswd.area2;
}
# 测试配置是否正确
sudo nginx -t
# 重新加载配置
sudo systemctl reload nginx
.htpasswd
文件放在Web根目录之外bash
sudo chown root:www-data /etc/nginx/.htpasswd
sudo chmod 640 /etc/nginx/.htpasswd