首页 文章

Nginx根据用户登录提供不同的文件?

提问于
浏览
4

我正在使用Node.js和nginx . 我的节点应用程序基于快速构建,使用护照进行身份验证并使用会话 . 我的节点应用程序响应所有 /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,但是当用户注销时似乎没有消失 .

1 回答

  • 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
    }
    

相关问题