nginx用户认证配置( Basic HTTP authentication)

在一些场景下,网站需要些简单的账号密码认证,可以使用nginx默认自带的http认证-ngx_http_auth_basic_module模块,在认证之前网页会显示 401 Authorization Required ,认证成功后可以显示正常的网页内容。

既然认证就要先准备好账号密码了~认证需要的密码加密需要htpasswd,或者openssl。这里采用htpasswd。
首先安装httpd

yum -y install httpd

创建认证文件,输入两次密码后文件就创建了

htpasswd -c /etc/nginx/httppasswd test
New password: 
Re-type new password: 
Adding password for user test

nginx配置添加

auth_basic "Auth Page";
auth_basic_user_file /etc/nginx/httppasswd;
autoindex on;

完整nginx配置示例

server
{
  listen 80;
  server_name   www.test.com;
  root          /data/wwwroot/www.test.com/public_html;
  index         index.php index.html;
  
  location /
  {
  auth_basic "Auth Page";
  auth_basic_user_file /etc/nginx/httppasswd;
  autoindex on;
  }

  location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi.conf;
  }
}

重启nginx

nginx -s reload

 

Leave A Comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked