我只想在使用后端进行身份验证后显示我的文档(使用React构建的单页应用程序(。
我的配置:
- Nginx充当后端(Django(的反向代理,并像单页应用程序一样提供静态文件
- 后台Django识别用户并使用X-Accel-Rerect向Nginx发出请求
所以我按如下进行:
1(Django上的身份验证
视图.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_request标签移动到位置之外的顶级,就可以使整个服务器都需要auth-my
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;
}
}