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: http://www.example.com -> http://example.com

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 http://no-www.org/ for details.

And, without further ado:

http://gist.github.com/224812

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:

Rails::Initializer.run do |config|
  config.middleware.use “NoWWW” if RAILS_ENV == ‘production’
end

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.