Nginx 可以通过 HTTP 基本认证(Basic Authentication)来配置用户验证页面,保护特定的目录或网站。以下是详细的配置步骤:
首先需要创建一个包含用户名和密码的文件:
sudo sh -c "echo -n 'username:' >> /etc/nginx/.htpasswd"
sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"
或者使用 htpasswd
工具(需要安装 apache2-utils):
sudo apt-get install apache2-utils # Debian/Ubuntu
sudo yum install httpd-tools # CentOS/RHEL
sudo htpasswd -c /etc/nginx/.htpasswd username
要添加更多用户(不覆盖现有文件):
sudo htpasswd /etc/nginx/.htpasswd anotheruser
在 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 /protected/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
}
}
location ~ \.php$ {
auth_basic "PHP Files Protected";
auth_basic_user_file /etc/nginx/.htpasswd;
# PHP处理配置...
}
sudo nginx -t # 测试配置语法
sudo systemctl reload nginx # 或 sudo service nginx reload
location /protected/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
location /protected/public/ {
auth_basic off;
}
}
location /admin/ {
satisfy all; # 需要同时满足IP和认证
allow 192.168.1.0/24;
deny all;
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
auth_basic_user_file /etc/nginx/.htpasswd;
auth_basic "Different Realm Name";
这样配置后,访问受保护的页面时浏览器会弹出登录对话框,要求输入用户名和密码。