Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to canonical route in without trailing slash in Rails 3

On Rails 3, I'm trying to redirect from a URL without a trailing slash to the canonical URL that has a slash.

match "/test", :to => redirect("/test/")

However, the route above matches both /test and /test/ causing a redirect loop.

How do I make it match only the version without the slash?

like image 861
Shai Coleman Avatar asked Dec 17 '22 06:12

Shai Coleman


2 Answers

You can force the redirect at the controller level.

# File: app/controllers/application_controller.rb
class ApplicationController < ActionController::Base

  protected

  def force_trailing_slash
    redirect_to request.original_url + '/' unless request.original_url.match(/\/$/)
  end
end

# File: app/controllers/test_controller.rb
class TestController < ApplicationController

  before_filter :force_trailing_slash, only: 'test'  # The magic

  # GET /test/
  def test
    # ...
  end
end
like image 177
Blake Taylor Avatar answered May 08 '23 10:05

Blake Taylor


I wanted to do the same to have a cannonical url for a blog, this works

  match 'post/:year/:title', :to => redirect {|env, params| "/post/#{params[:year]}/#{params[:title]}/" }, :constraints => lambda {|r| !r.original_fullpath.end_with?('/')}
  match 'post/:year/:title(/*file_path)' => 'posts#show', :as => :post, :format => false

then I have another rule which deals with the relative paths inside the post. Order is important, so former goes first and generic one goes second.

like image 22
carlosayam Avatar answered May 08 '23 10:05

carlosayam