Using Rack::Rewrite to remove the www

Rack::Rewrite is a pretty useful tool. It allows you to change the location of a url or perform 301 or 302 redirects using rack. The real benefit of this is that the logic of your routes is contained within your app and server agnostic. Sure there is a performance hit compared to using mod-rewrite etc. in Apache, Nginx and so on but we feel its worth it in most cases. If you are using caching systems like varnish or squid the redirect can be cached too.

Using Rack::Rewrite to go NoWWW

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/.

If you are already using Rack::Rewrite though you may as well just use that to make the change. The following is a rule to make the no-www change using rack middleware.

r301 /.*/,  Proc.new {|path, rack_env| "http://#{rack_env['SERVER_NAME'].gsub(/www\./i, '') }#{path}" },
    :if => Proc.new {|rack_env| rack_env['SERVER_NAME'] =~ /www\./i}
Advertisements