Jim Neath

Manchester based Ruby on Rails & Facebook App Developer

NGINX is an awesome server, but unfortunately contains an error in earlier versions (pre 0.8.32), that sends the incorrect headers for 201 (created) responses. It does not set the Content-Length header, which causes modern browsers to keep the connection open and wait until the timeout value is exceeded.

There are two possible fixes for this; Upgrade NGINX to version 0.8.32 or greater, or fix the issue in your server side code. I’ll show you how we can do the latter, using Rack.

Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.

We will use a piece of Rack middleware to set the correct headers for any 201 responses.

Copy the code below into lib/content_length_fix.rb:

module Nginx
  class ContentLengthFix
    def initialize(app)
      @app = app       

    def call(env)
      status, headers, response = @app.call(env)
      headers["Content-Length"] = response.length.to_s if status == 201
      [status, headers, response]

Then add the following to your config.ru file:

require 'content_length_fix' 
use Nginx::ContentLengthFix

Rejoice and your 201 responses now have the correct headers set!

blog comments powered by Disqus

I am available for freelance work! Click here to email me.

Jim Neath is a Freelance Ruby on Rails & Facebook app developer from Manchester, UK, currently working for Engine Yard.