3

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

Victor Ferreira
  • 6,151
  • 13
  • 64
  • 120

2 Answers2

3

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

Community
  • 1
  • 1
Pavel Tkackenko
  • 963
  • 7
  • 20
  • 1
    Why is it better to do it in nginx or apache? – mhutter Sep 08 '15 at 15:56
  • Because further you may face a problem of redirecting from http to https for example. Because nginx is written using C with focusing on such tasks, so it will be faster than Rails. – Pavel Tkackenko Sep 09 '15 at 06:58
2

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
mhutter
  • 2,800
  • 22
  • 30
spickermann
  • 100,941
  • 9
  • 101
  • 131