仅针对给定位置的 Nginx 身份验证

Yar*_*nST 2 nginx authentication http-authentication http-basic-authentication

我使用 Nginx 作为 python WSGI web-app 的反向代理。

它看起来像这样:

location / {
    #auth_basic     "Administrator Login";
    #auth_basic_user_file  /var/www/static/.htpasswd;
    proxy_pass          http://mywebapp_gunicorn;
    proxy_redirect      off;
    proxy_set_header    Host            $host;
    proxy_set_header    X-Real-IP       $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
}
Run Code Online (Sandbox Code Playgroud)

在 Web 应用程序内部,我有一些管理员页面,我希望受到很好的保护,所以现在我在 Web 应用程序内部使用了一些身份验证来保护它们,我也想添加 Nginx 身份验证。

如何激活:

    auth_basic      "Administrator Login";
    auth_basic_user_file  /var/www/static/.htpasswd;
Run Code Online (Sandbox Code Playgroud)

对于 path: /managers,但不适用于所有其他 URL。

Dan*_*ack 7

您只需要当前拥有的位置块之前添加另一个位置块,以匹配您想要保护的 url。

location /managers {
    auth_basic      "Administrator Login";
    auth_basic_user_file  /var/www/static/.htpasswd;
    proxy_pass          http://mywebapp_gunicorn;
    proxy_redirect      off;
    proxy_set_header    Host            $host;
    proxy_set_header    X-Real-IP       $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
}

location / {
    proxy_pass          http://mywebapp_gunicorn;
    proxy_redirect      off;
    proxy_set_header    Host            $host;
    proxy_set_header    X-Real-IP       $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
}
Run Code Online (Sandbox Code Playgroud)

因为它在/1之前,它将优先用于路径 /managers 。

  • `location` 块出现的顺序无关紧要。 (3认同)