Report this

What is the reason for this report?

How to Enabling Session Persistence using nginx

Posted on August 27, 2020

Looking for some details on how we can persist sessions which will work for both web apps (using cookie for JSESSIONID) and Mobile apps (which may be using request header with session information)



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hello,

You can configure Nginx to use sticky sessions by enabling session persistence. For this you need to use the sticky directive in the http context of your Nginx configuration. However, it’s worth noting that this functionality is only available in Nginx Plus, the commercial version of Nginx.

In the http block, use the sticky directive:

http {
    upstream backend {
        server backend1.example.com;
        server backend2.example.com;
        sticky cookie srv_id expires=1h domain=.example.com path=/;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://backend;
        }
    }
}

In this configuration, Nginx sets a cookie named srv_id on the first request from a client. For future requests from the same client, the client’s browser will send the srv_id cookie, and Nginx will route the request to the same backend server as previous requests from this client.

However, for apps or clients which do not support cookies, such as some mobile apps, you would need to implement session persistence in your application logic. One common way to do this is to use a distributed cache or a database to store session information.

For example, you could use a distributed cache like Redis to store session data. When a client makes a request, your application can check if there’s a session ID in the request headers, and if there is, retrieve the corresponding session data from Redis.

Managed Redis

If you’re using Node.js, there are middleware libraries available for managing sessions with various stores, such as express-session for Express.js.

Best,

Bobby

Enabling session persistence in Nginx typically involves using the ip_hash directive for load balancing scenarios, where you need to ensure that a client is consistently served by the same backend server. However, for session persistence that works across different types of clients (like web and mobile apps), you may need to look beyond basic Nginx configurations, especially if your session management doesn’t rely solely on IP addresses.

Here’s a general approach to handling session persistence:

1. Using ip_hash for Basic Session Persistence

If your application can work with session persistence based on client IP addresses, you can use the ip_hash directive in an Nginx upstream block. This method is straightforward and works well for simple scenarios:

upstream backend {
    ip_hash;
    server backend1.example.com;
    server backend2.example.com;
}

In this configuration, requests from the same client IP address will be sent to the same backend server.

2. Sticky Sessions Using ngx_http_upstream_module

For more advanced session persistence (like sticky sessions based on cookies), you might need to use the ngx_http_upstream_module with a compatible third-party module (like nginx-sticky-module or ngx_http_sticky_module). These modules allow you to create a sticky session based on cookies.

An example configuration might look like this:

upstream backend {
    sticky cookie srv_id expires=1h domain=.example.com path=/;
    server backend1.example.com;
    server backend2.example.com;
}

In this setup, the sticky directive instructs Nginx to use a cookie named srv_id to track the backend server for each client.

3. Session Persistence for Mobile Apps

For mobile apps that don’t rely on cookies, you’ll need a more customized approach. Often, mobile apps use tokens or custom headers for session management. In such cases, session persistence needs to be managed at the application level rather than the Nginx level.

  • Application-Level Session Management: Your backend application can handle sessions by mapping tokens or custom headers to specific user sessions. This approach is more flexible and can accommodate various client types.

  • Custom Nginx Configuration: If you’re looking to handle this at the Nginx level, you would need a more advanced setup, possibly involving custom modules or Lua scripting with ngx_http_lua_module to parse request headers and implement session logic.

4. Security Considerations

When implementing session persistence, especially with cookies, ensure you follow security best practices:

  • Use secure and HTTP-only flags for cookies.
  • Consider the implications of session persistence on your application’s load balancing and fault tolerance.

5. Testing and Validation

After setting up session persistence, thoroughly test your configuration with different client types to ensure that sessions are being persisted as expected.

Conclusion

The specific approach to session persistence will depend on your application’s architecture and requirements. For simple scenarios, ip_hash or sticky sessions might suffice, but for more complex situations involving various client types, you may need to implement session management at the application level or use advanced Nginx configurations.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.