no-www Rack Middleware

I’m pleased to present my submission to the CodeRack contest: no-www.

This middleware catches requests that begin with “www” and redirects them to the more reasonable “non-www” address.

For example: ->

While such redirects might better be performed from within an Apache or nginx config, some hosts (i.e. Heroku) don’t give you access to configure the server as such.

If you’re unfamiliar with the no-www movement, the philosophy is simple. Websites should have a canonical address. This address shouldn’t begin with “www” because the use of “www” is unnecessary and wasteful. See for details.

And, without further ado:

If you know what Rack is, you problably already know how to use this. Still, an example usage for a Rails app wouldn’t hurt. Start by copying the above middleware into lib/no_www.rb. Then, configure your application to use the middleware by placing the following in config/environment.rb: do |config|
  config.middleware.use “NoWWW” if RAILS_ENV == ‘production’

No more www.


Published by

Trevor Turk

A chess-playing machine of the late 18th century, promoted as an automaton but later proved a hoax.