Authentication Nginx基本身份验证不工作

Authentication Nginx基本身份验证不工作,authentication,nginx,configuration,Authentication,Nginx,Configuration,我正试图在我的Nginx配置中保护默认服务器。但是,当我访问该站点时,不会显示用户名/密码对话框。Nginx像往常一样返回内容。以下是完整的配置: worker_processes 1; events { multi_accept on; } http { include mime.types; sendfile on; tcp_nopush on; keepalive_timeout 30;

我正试图在我的Nginx配置中保护默认服务器。但是,当我访问该站点时,不会显示用户名/密码对话框。Nginx像往常一样返回内容。以下是完整的配置:

worker_processes 1;

events
{
    multi_accept on;
}

http
{
    include       mime.types;
    sendfile           on;
    tcp_nopush         on;
    keepalive_timeout  30;
    tcp_nodelay        on;
    gzip  on;

    # Set path for Maxmind GeoLite database
    geoip_country /usr/share/GeoIP/GeoIP.dat;

    # Get the header set by the load balancer
    real_ip_header   X-Forwarded-For;
    set_real_ip_from 0.0.0.0/0;
    real_ip_recursive on;

    server {
        listen       80;
        server_name  sub.domain.com;

        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/htpasswd/sub.domain.com.htpasswd;

        expires -1;

        access_log /var/log/nginx/sub.domain.com.access default;
        error_log  /var/log/nginx/sub.domain.com.error debug;

        location / {
            return 200 '{hello}';
        }
    }
}
有趣的是,当我尝试使用无效的文件路径作为auth_basic_user_file的值时,configtest仍然通过。事实不应如此

以下是Nginx和系统信息:

[root@ip nginx]# nginx -v
nginx version: nginx/1.8.0

[root@ip nginx]# uname -a
Linux 4.1.7-15.23.amzn1.x86_64 #1 SMP Mon Sep 14 23:20:33 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

我们正在使用可通过yum获得的Nginx RPM。

您需要将auth\u basic和auth\u basic\u user\u文件添加到位置块中,而不是服务器块中

location / {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd/sub.domain.com.htpasswd;
return 200 '{hello}';

    }

在将基本身份验证添加到配置后,您是否尝试重新加载/停止并启动nginx?有必要使用以下内容重新加载nginx:

sudo -i service nginx reload
----以使新设置生效

另外,我会仔细检查您测试的URL。 (有一次我尝试在一个Nginx代理配置中测试Nginx Basic Auth,该配置访问Nginx代理后面的资源的实际URL,而不是Nginx的实际URL。)


附笔。 使用无效的文件路径作为auth_basic_user_file的值也不会导致2018年的configtest失败。 以下是我的Nginx版本:

nginx version: nginx/1.10.2
尽管无效的文件路径会导致基本身份验证检查失败并导致:

403 Forbidden

----提供凭据后的HTTP响应。

在我的情况下,将指令添加到
/etc/nginx/sites available/default
有效,而将指令添加到
/etc/nginx/nginx.conf
无效

当然,只有在nginx.conf文件中包含以下内容时,才会发生这种情况:

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
配置很简单(将其放在网站特定部分的位置下,或整个网站的服务器下):

这是不正确的。
server
块中的allow
auth\u basic
auth\u basic\u user\u文件
。此外,for
ngx\u http\u auth\u basic\u模块
指定上下文可以是
http
服务器
位置
、或
限制
server {
        location /foo/ {
                auth_basic "This part of website is restricted";
                auth_basic_user_file /etc/apache2/.htpasswd;
        }
}