如何配置Nginx用户认证?
2025-04-14 11:31:08
82
参考资料
如何配置Nginx用户认证?
安装htpasswd工具(Apache工具包):
Ubuntu/Debian:
sudo apt-get install apache2-utilsCentOS/RHEL:
sudo yum install httpd-tools创建密码文件:
sudo htpasswd -c /etc/nginx/.htpasswd username
编辑Nginx配置文件(通常在
/etc/nginx/sites-available/default或/etc/nginx/conf.d/default.conf):server { listen 80; server_name example.com; location / { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/.htpasswd; } }测试并重载Nginx配置:
sudo nginx -t sudo systemctl reload nginx
完整示例:
server {
listen 80;
server_name mysite.com;
location /private/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置
proxy_pass http://localhost:8080;
}
} 
