具有双重授权的 gunicorn 的 Nginx

Nginx with gunicorn with double authorization

我想使用 http auth,但也想使用 gunicorn 的反向代理。

对于 http 身份验证,我使用:

location = admin.html {
 auth_basic 'Login Required'
 auth_basic__use_file etc/nginx/.htpasswd;
}

对于 gunicorn,代理反向我发现:

try_files $uri @gunicorn;

如何将两者结合起来?

您的意思是要使用 nginx 作为具有额外授权级别的 django 的反向代理服务器吗?您只需将 auth_basicauth_basic_user_file 指令从 location 块移动到 server 块:

upstream gunicorn_server {
    server unix:</path/to/socket/pseudo/file>;
}

server {
    listen ...;
    server_name ...;
    auth_basic "Login Required";
    auth_basic_user_file etc/nginx/.htpasswd;
    ... # other parameters
    location / {
        try_files $uri @gunicorn;
    }
    location @gunicorn {
        proxy_pass http://gunicorn_server;
    }
}

更新

假设有一个 "admin" 区域,其中包括 /admin.html/admin/any/other/uri 以使用 HTTP Basic Auth 额外保护该区域,您可以使用以下配置:

upstream gunicorn_server {
    server unix:</path/to/socket/pseudo/file>;
}

server {
    listen ...;
    server_name ...;
    ... # other parameters
    location / {
        try_files $uri @gunicorn;
    }
    location /admin {
        auth_basic "Login Required";
        auth_basic_user_file etc/nginx/.htpasswd;
        try_files $uri @gunicorn;
    }
    location @gunicorn {
        proxy_pass http://gunicorn_server;
    }
}

要保护单个文件 admin.htmllocation /admin { 替换为 location = /admin.html {