Valera
Valera

Reputation: 2923

Nginx return static file or proxied request depending on cookie value

I have two applications, one nodejs and another react app. I user is not logged in, I return the node app, if user is logged in, I want to return the react app index.html file.

location / {
    if ($cookie_isLoggedIn = "true") {
        // how can I return the index.html file here ?
    }
    proxy_pass http://localhost:3000;
}

What I tried so far:

  1. rewrite ^/$ /platform-build/index.html; - doesn't do anything.
  2. alias and root are not working inside if statement.

Upvotes: 0

Views: 804

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15547

You need to use two different content handlers (proxy_pass and try_files), so you need two different locations for that. You can return some static HTML content via the directive like

return 200 "<body>Hello, world!</body>";

but I don't think it will satisfy your needs. However you can use the following trick (taken from this answer):

map $cookie_isLoggedIn $loc {
    true    react;
    default node;
}
server {
    ...
    location / {
        try_files /dev/null @$loc;
    }
    location @react {
        root /your/react/app/root;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
    location @node {
        proxy_pass http://localhost:3000;
    }
}

The author of original trick says it doesn't have any performance impact.

Upvotes: 1

Related Questions