7

In order to avoid content duplication, I would like to avoid the pages of my site being accessible by several URLs (with or without trailing slash).

Currently, the URLs

catalog/product/1

and

catalog/product/1/

lead to the same page. My goal is that the second URL redirect to the first (redirection 301, of course). None page of my site should be accessible with a trailing slash, except my home page / obviously.

What is the best way to do this? Using .htaccess or routes.rb? How would you do that?

NB: I'm developing with Ruby on Rails 1.2.3

John Topley
  • 113,588
  • 46
  • 195
  • 237
Flackou
  • 3,631
  • 4
  • 27
  • 24

4 Answers4

16

You could use http://github.com/jtrupiano/rack-rewrite for url rewriting to be independent from differences in web-servers.

Example usage in rails application:

config.gem 'rack-rewrite', '~> 1.0.0'
require 'rack/rewrite'
config.middleware.insert_before(Rack::Lock, Rack::Rewrite) do
  r301 %r{(.+)/$}, '$1'
end
lest
  • 7,780
  • 2
  • 24
  • 22
  • 6
    In Rails 4, you'll need to replace `Rack::Lock` with `Rack::Runtime` (or another), as `Rack::Lock` is not present in the multi-threaded Rails environment enabled by default in Rails 4. – William Denniss Jun 16 '13 at 10:04
  • This doesn't remove trailing `/` when there is a query parameters. – Amit Patel Oct 07 '20 at 13:13
9

I'd use Apache's mod_rewrite. Try this:

RewriteEngine on
RewriteRule ^(.+)/$ $1 [R=301,L]

EDIT: Added R=301. I'm guessing there is an SEO advantage to that vs. the default 302.

Sarah Mei
  • 18,154
  • 5
  • 45
  • 45
  • Thanks for the answer. I just tested it and observed a strange behaviour : it rewrites the URL adding the absolute path of the page! For instance, if I try to access to http://www.mysite.com/test/, it redirects to http://www.mysite.com/home/mysite/public_html/test !! Do you understand that? – Flackou Mar 10 '09 at 23:11
  • 1
    Hmm, you might need to add "RewriteBase /" before the RewriteRule line. – Sarah Mei Mar 11 '09 at 00:23
2

You can do this using the rack-rewrite gem. Here's how: http://nanceskitchen.com/2010/05/19/seo-heroku-ruby-on-rails-and-removing-those-darn-trailing-slashes/

DougB
  • 674
  • 7
  • 14
0

You can't get a redirect using routes.rb. I suppose you could build a controller that just issues redirects and point all URLs ending in '/' to it, but that seems needlessly complicated. Instead, I'd use mod_rewrite in a .htaccess file:

RewriteRule ^(.+)/$ $1 [R=301,L]
Pesto
  • 23,810
  • 2
  • 71
  • 76