Nginx set session-cookie before upstreams are hit

nginxsession

We have a nginx-reverse-proxy/cache and multiple backend-servers.

My current problem with our setup is that if a user hits a cached site he / she does not get a session-cookie set, as the backend is not hit.
This is clearly the expected behavior.

In our case, however, I want the reverse-proxy to send a session-cookie with the cached response even before any of the backend-servers are hit.

I know I can use

 add_header Set-Cookie

for this but how can I

  • make sure the cookie is only set once?
  • generate a cookie in the form of a uuid which is not hardcoded?

Best Answer

You could try to replicate the session cookie generating logic of your application software with nginx lua language.

However, a better way to implement this would be to use a JavaScript on your page that calls an URL in your page where it gets a session cookie.