Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a URL's trailing slash in a Rails app? (in a SEO view)

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

like image 674
Flackou Avatar asked Mar 09 '09 16:03

Flackou


Video Answer


3 Answers

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
like image 189
lest Avatar answered Oct 12 '22 12:10

lest


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.

like image 24
Sarah Mei Avatar answered Oct 12 '22 13:10

Sarah Mei


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/

like image 43
DougB Avatar answered Oct 12 '22 12:10

DougB