Question

I am using Node.js with nginx. My Node app is built on express and uses passport for authentication and is using sessions. My Node app is responding to JSON requests on all /api urls, and nginx is serving static files from a public directory.

I want nginx to serve index.html at / when the user is not logged in, and serve app.html at / when the user is logged in.

Here's my current nginx config.

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

How do I get nginx to determine if a user is logged in or not, and then serve a different file accordingly? I've noticed that express creates a cookie called connect.sid, but that doesn't seem to go away when the user logs out.

Était-ce utile?

La solution

Only application could check if user is logged in or not, but you could use X-Accel-Redirect header to make nginx serve one file or another.

Some pseudocode:

if (user.isLoggedIn) {
    response.setHeader("X-Accel-Redirect", "/app.html");
} else {
    response.setHeader("X-Accel-Redirect", "/index.html");
}
response.end();

Also you need to pass request to / to application.

location = / {
    # copy from location /api
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top