Nginx与gunicorn双重授权

use*_*631 5 python nginx gunicorn

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

对于http auth,我使用:

location = admin.html {
 auth_basic 'Login Required'
 auth_basic__use_file etc/nginx/.htpasswd;
}
Run Code Online (Sandbox Code Playgroud)

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

try_files $uri @gunicorn;
Run Code Online (Sandbox Code Playgroud)

我如何将两者结合起来?

Iva*_*sky 8

你的意思是你想使用nginx作为django的反向代理服务器以及额外的授权级别吗?您只需将您的auth_basicand auth_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;
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

假设有一个"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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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