Nginx:如何在身份验证后使用单个内部指令提供多个内容

Nginx : How to serve multiple contents with a single internal directive after authentication

我只想在后端验证后显示我的文档(用 React 构建的单页应用程序)。

我的配置:

所以我进行如下操作:

1) Django 上的身份验证

views.py

def get_doc(request):
    if request.method == 'POST':
        form = PasswordForm(request.POST)
        if form.is_valid():
            if form.cleaned_data['password'] == 'foo':
                 response = HttpResponse()
                 response['Content-Type'] = ''
                 response['X-Accel-Redirect'] = '/docs-auth/'
                 return response
            else:
                return HttpResponse("Wrong password")
    else:
        form = PasswordForm()
    return render(request, 'docs/form.html', {'form': form})

urls.py

urlpatterns = [
    path('docs/', views.get_doc, name='documentation'),
]

2) Nginx服务单页应用

upstream backend {
       server web:8000;
}

server {
       location = /favicon.ico {access_log off;log_not_found off;}

       ...

       location /docs {
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header Host $host;
         proxy_redirect off;
         proxy_pass http://backend;
       }

       location /docs-auth/ {
         internal;
         alias /home/foo/docs/;
         index index.html;
         try_files $uri $uri/ /docs/index.html;   
       }

       location / {
         alias /home/foo/landing_page/;
         error_page 404 /404.html;
         index index.html;
         try_files $uri $uri/ =404;
       }
}

我的问题是 index.html 文件已提供给用户,但随后浏览器请求访问 CSS 和 Javascript 文件被 阻止因为浏览器无法访问内部url.

你有什么办法解决我的问题吗?

我也愿意接受另一种在后端身份验证后为单页应用程序提供服务的方式。

非常感谢。

您想使用 auth_request 标签让您的生活更轻松。这是一个示例,您将需要对您的配置进行改造。你可以让你的整个服务器需要 auth 我只是将 auth_request 标签移动到 location

之外的顶层
 server {
   ...

   location /docs {
     auth_request     /docs-auth;

     ...// Add your file redering here
   }

   location = /docs-auth {
        internal;
        proxy_pass              http://auth-server;
        proxy_pass_request_body off;
        proxy_set_header        Content-Length "";
        proxy_set_header        X-Original-URI $request_uri;
   }
 }