8

I added slugs to some of the models, but because of SEO I need to do 301 redirection from old links: old:

http://host.com/foo/1

new:

http://host.com/foo/foo_slug

question: how to implement 301 redirection in this case? and is it possible to implement 301 redirection from uppercased link? Like this:

http://host.com/foo/FOO_SLUG -> http://host.com/foo/foo_slug
Stuart M
  • 11,458
  • 6
  • 45
  • 59
xamenrax
  • 1,724
  • 3
  • 27
  • 47

2 Answers2

18

You should be able to redirect with status 301 by adding this to your controller action:

redirect_to "http://host.com/foo/foo_slug", :status => 301

See the API documentation for redirect_to for details.

And there should be no problem with redirecting upper-cased URLs to lowercased versions, although this may be better handled by something at the HTTP server layer such as Apache mod_rewrite rules.

Stuart M
  • 11,458
  • 6
  • 45
  • 59
  • .. or the nginx config. passengers seems to be more popular on nginx – scones Apr 08 '13 at 06:45
  • Thank you for answer, also, Rails 3 allows to create 301 redirects directly from routes.rb, is it better to do it in controller or in the routes? – xamenrax Apr 08 '13 at 07:29
  • 1
    In your case I think you will have to do it in the controller action, since I assume you are going to be looking up the slug from a database? If so, the code to look up a record and find its slug can only occur within a controller action, not within `routes.rb` – Stuart M Apr 08 '13 at 07:31
  • 1
    I just need to check is there in params old `:id`, and if yes redirect to instance_path with correct slugged `:id`? – xamenrax Apr 08 '13 at 08:31
  • Right, but in order to translate the `:id` into the corrected slug, you have to run a database query right? If so, it must be done in a controller, not in routes – Stuart M Apr 08 '13 at 08:32
  • One more question - what is the better way to handle 301 redirection if this case: `http://host.com/bars/:id////////(random number of slashes)` -> `301` -> `http://host.com/bars/:id`? – xamenrax Apr 08 '13 at 09:28
  • 1
    I would think that the same `redirect_to` call would be able to handle it, as long as your Rails routes correctly route the URL with a lot of slashes to your controller route containing the redirect. – Stuart M Apr 08 '13 at 16:21
2

For 301 redirection write this code in your controller:

headers["Status"] = "301 Moved Permanently"

redirect_to "http://host.com/foo/foo_slug" # in your case

And for second question, use capitalise or down case if you mentioned hardcode url.

Otherwise use ruby interpolation by putting whole url in string

prasad_g
  • 139
  • 8
  • Rather than hard-code the `Status` header, why not just pass `:status => 301` and let Rails handle formatting that header (see my answer for an example) – Stuart M Apr 08 '13 at 06:49