Search

Redirect www Subdomain to Your Apex Domain Using the Rails Router

Steven Harman

2 min read

Aug 27, 2012

Redirect www Subdomain to Your Apex Domain Using the Rails Router

No www. - 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..

Also easy, just more dub-dubs.

To www. or not?

Do you have a preference or just an argument? Let’s hear it!

Mark Dalrymple

Reviewer Big Nerd Ranch

MarkD is a long-time Unix and Mac developer, having worked at AOL, Google, and several start-ups over the years.  He’s the author of Advanced Mac OS X Programming: The Big Nerd Ranch Guide, over 100 blog posts for Big Nerd Ranch, and an occasional speaker at conferences. Believing in the power of community, he’s a co-founder of CocoaHeads, an international Mac and iPhone meetup, and runs the Pittsburgh PA chapter. In his spare time, he plays orchestral and swing band music.

Speak with a Nerd

Schedule a call today! Our team of Nerds are ready to help

Let's Talk

Related Posts

We are ready to discuss your needs.

Not applicable? Click here to schedule a call.

Stay in Touch WITH Big Nerd Ranch News