我正在使用带有nginx的Node.js。我的节点应用程序基于快速构建,并使用护照进行身份验证并使用会话。我的节点应用正在响应所有/api
网址上的JSON请求,而nginx正在从公共目录提供静态文件。
我希望nginx在用户未登录时在index.html
提供/
,并在用户登录时在app.html
提供/
。
这是我当前的nginx配置。
upstream app_upstream {
server 127.0.0.1:3000;
keepalive 64;
}
server {
listen 0.0.0.0:80;
server_name app.com default;
access_log /var/log/nginx/app.com.access.log;
error_log /var/log/nginx/app.com.error.log debug;
root /home/app/app/public;
location /api {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_cache_bypass 1;
proxy_no_cache 1;
expires off;
if_modified_since off;
add_header Last-Modified "";
proxy_pass http://app_upstream;
proxy_redirect off;
}
location / {
access_log off;
expires max;
}
}
如何让nginx确定用户是否已登录,然后相应地提供其他文件?我注意到express创建了一个名为connect.sid
的Cookie,但在用户退出时似乎并没有消失。
答案 0 :(得分:5)
只有应用程序可以检查用户是否已登录,但您可以使用X-Accel-Redirect
标头使nginx提供一个或另一个文件。
一些伪代码:
if (user.isLoggedIn) {
response.setHeader("X-Accel-Redirect", "/app.html");
} else {
response.setHeader("X-Accel-Redirect", "/index.html");
}
response.end();
您还需要将请求传递给/
到应用程序。
location = / {
# copy from location /api
}