Redirect www Subdomain to Your Apex Domain Using the Rails Router

It’s 2012. We know it’s the World Wide Web. We don’t need to be reminded of
that by prepending www. to the URL of every site we visit. In fact, the use of www. as the
de facto subdomain of The Web was an accident. And
what’s more, it was deprecated back in August of 2003.

I am over www. and hereby pledege to do my best to stop using it on the
portions of the Internet that I build. To be successful, I need the Ruby on
Rails-powered apps I create to also drop the dubs. The powerful
router in Rails 3 (and newer) makes this trivial. Peep this:

Let’s talk about what’s going on there…

Routing Constraints

That outermost constraints block is a Rails routing constraint
that only matches requests where the host starts with www.. When that
constraint is met, we match ALL THE PATHS and any HTTP verb. Upon making the match, we tell the router
to redirect the request to a new URL.

The new URL is whatever URL the request came in on, sans the leading www..

Easy peasy!

What if you want the dub-dub-dub?

For starters, I’ll hold it against you. But then I’ll immediately get over it
and we’ll go back to being friends.

In fact, as a token of my friendship, I’ll show you how to redirect non-www.
requests to a www.-version.

This works much like the first example, but in reverse. An incoming request
lacking a leading www. matches our constraint and gets redirected to the same
URL prefixed with a www..