no-www Rack Middleware
by Trevor Turk
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:
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.
[...] no-www Rack Middleware [...]
Thanks! Nice and simple.
[...] almost effortless » no-www Rack Middleware [...]
[...] There has been a bit of a movement for a while on the web to deprecate www. in front of domain names called no-www. As the site says the title www isn’t really of any use anymore. As well as the no-www movement having a single host can also be useful for things like analytics and cleaning up search results. There are a couple of rails solutions to doing this including a peice of rack middleware at this site http://almosteffortless.com/2009/11/05/no-www-rack-middleware/. [...]