Nginx基本身份验证无法工作

4

我正在尝试在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的值时,配置测试仍然通过。这不应该是这种情况。
以下是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包。
3个回答

1
你需要在位置块中添加auth_basic和auth_basic_user_file,而不是服务器块。
location / {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd/sub.domain.com.htpasswd;
return 200 '{hello}';

    }

5
这是错误的。 Nginx文档允许在server块中使用auth_basicauth_basic_user_file - Daniel Morell
此外,ngx_http_auth_basic_module文档指定其上下文可以是 httpserverlocationlimit_except - Daniel Morell

0
你尝试在配置文件中添加基本身份验证后重新加载/停止和启动您的nginx了吗?需要使用类似以下命令重新加载nginx:
sudo -i service nginx reload

----为了使新的设置生效。

此外,我建议您仔细检查测试中使用的URL。在我的一次尝试中,我测试了Nginx基本身份验证,在Nginx代理配置中访问实际资源的URL而不是Nginx的实际URL,结果导致测试失败。


附言

在2018年,将无效的文件路径用作auth_basic_user_file的值仍不会导致configtest失败。 这是我的Nginx版本:

nginx version: nginx/1.10.2

虽然无效的文件路径会导致基本身份验证检查失败并导致以下结果:

403 Forbidden

---- 提供证书后的HTTP响应。


0
在我的情况下,将指令添加到/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 {
        location /foo/ {
                auth_basic "This part of website is restricted";
                auth_basic_user_file /etc/apache2/.htpasswd;
        }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接