making nginx return HTTP errors randomly

It’s been a while since I last posted, so let’s write a tiny hack I did because I wanted to get random errors from an nginx server.

location / {
  return 200 "Hello $remote_addr, I am $server_addr\n";

location /healthz {
  set_by_lua_block $health {
    local x = math.random(1, 100)
    if x <= 20 then return 500 else return 200 end

  if ($health = 200) {
    return 200 "OK\n";

  return 500;

The above snippet recognizes your IP address and greets you when you hit any URL on the web server. However, when you hit /healthz, then 20% of the time it returns Internal Server Error (HTTP 500). So your monitor might get tricked into thinking the application is not working as expected.

Bear in mind that the Lua PRNG is not seeded and if you plan to use this more seriously you need to initialize the Lua module and seed the PRNG properly. Otherwise you will always get errors at the exact sequence of calls.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s