Tasty Cookies with nginx

In a previous post I talked about the best way to handle putting an application into maintenance mode. In addition to sending the appropriate status code (503) for machines, nginx is configured to serve a helpful page to inform users of the maintenance window. Today, I would like to build on this configuration to make it possible for a few users to test the application while it is in maintenance mode for the rest of the world. There are a few different ways this could be handled, but HTTP cookies are a simple and flexible solution.

Recall these directives which instruct nginx to check for our maintenance page and set the status code to 503:

if (-f $document_root/system/maintenance.html) {
  return 503;
}

Let’s modify this with a variable to track state. Now, we can add an additional check for anything we would like to turn $maint off. $http_cookie holds all the cookies for the request:

set $maint off;

if (-f $document_root/system/maintenance.html) {
  set $maint on;
}

if ($http_cookie ~* "topsekrit" ) {
  set $maint off;
}

if ($maint = on) {
  return 503;
}

You can now set a cookie with a value of “topsekrit” and nginx will let you circumvent the maintenance page to test your new code before you release it to the world.

One thought on “Tasty Cookies with nginx

Comments are closed.