Victor Ferreira
Victor Ferreira

Reputation: 6449

Add WWW to URL when it's not present on Ruby on Rails

I want to force my URL to start with www. when it's not present.

I tried the match method, but it seems to ignore the start of the URL, it seems to do something called Route Globbing, that appearently just works with route segments http://guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments

How do I make my application in RoR always start with www. ? -> www.foo.com must remain as it is -> foo.com must be redirected to www.foo.com

Upvotes: 3

Views: 490

Answers (2)

spickermann
spickermann

Reputation: 106882

You might consider a rack middleware like rack-www or rack-rewrite. Setup of rack-www is only two steps:

# Add to Gemfile (and run `bundler`)
gem 'rack-www'

# configure middleware via `application.rb` (for all environments)
# or the environment specific configuration file
# `environments/<environment>.rb`
config.middleware.use Rack::WWW, :www => true

Upvotes: 2

Pavel Tkackenko
Pavel Tkackenko

Reputation: 953

It's better to do it in nginx or apache (depends on what you're using). Please see these topics:

For nginx Nginx no-www to www and www to no-www

For Apache apache redirect from non www to www

Upvotes: 3

Related Questions