54

Is it possible to do a redirect in the routes file of a Rails app?

Specifically, I'd like to forward /j/e to /javascripts/embed.js

Right now the only way I can think to do it is to create a j controller with an e method that redirects to that.

Shpigford
  • 24,748
  • 58
  • 163
  • 252

3 Answers3

182

In Rails 4 and above

get '/stories', to: redirect('/posts')

In case you need a named route, you may want to add an explicit as parameter:

get '/stories', to: redirect('/posts'), as: :however_you_want_to_name_it

Source: Redirection @ guides.rubyonrails.org


In Rails 3, you can redirect inside the routes.rb file.

match "/posts/github" => redirect("http://github.com/rails.atom")
BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Steven Soroka
  • 19,404
  • 4
  • 52
  • 40
  • 9
    See [http://guides.rubyonrails.org/routing.html#redirection](http://guides.rubyonrails.org/routing.html#redirection) – user664833 Jul 18 '12 at 03:10
  • 8
    Thanks! I also needed to include an id in my redirect. For those that need it /:id/ in the match can be referenced as /%{id}/ in the redirected url... – Doug English Nov 21 '12 at 13:18
  • 8
    In Rails 4, `get '/stories', to: redirect('/posts')`, as seen in the [RoR Guides](http://edgeguides.rubyonrails.org/routing.html#redirection). Note that you don't need to create a view since you're redirecting at the routes level. – Dennis Feb 12 '14 at 16:33
  • In rails 4.2, using `to:` in `routes.rb` is deprecated. – Augustin Riedinger Nov 13 '15 at 00:10
  • 1
    @AugustinRiedinger the RoR guide for 4.2.6 says otherwise: http://guides.rubyonrails.org/routing.html#redirection – Nuri Hodges Mar 09 '16 at 20:21
8

Assuming rails version prior to 3.

You can create a new RedirectController or tuck a single function away in an existing controller, to do something like the following:

map.js_embed '/j/e',
    :controller => :redirect_controller,
    :action => :some_function,
    :path => "embed"

Then your function would do this:

def some_function
  if params[:path]
    redirect_to "/javascripts/#{params[:path]}.js"
  end
end

or something for that effect.

Outside_Box
  • 447
  • 1
  • 4
  • 16
Tony Fontenot
  • 5,091
  • 1
  • 21
  • 19
-1

Root path

You can make the root path redirect to an external website:

root to: redirect('https://www.lucascaton.com.br/en')
Lucas Caton
  • 3,027
  • 1
  • 24
  • 34