4

레일 3에서 슬래시가있는 표준 URL에 후행 슬래시가없는 URL에서 리디렉션하려고합니다.레일 3에 후행 슬래시없이 표준 경로로 리디렉션

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

그러나 위 경로는/test와/test /가 모두 일치하여 리디렉션 루프가 발생합니다.

슬래시가없는 버전과 어떻게 만듭니 까?

답변

2

ActionDispatch에 trailing_slash이라는 옵션이 있습니다.이 옵션을 사용하면 URL의 끝에 슬래시를 사용할 수 있습니다. 라우팅 정의에 사용할 수 있는지 확실하지 않습니다.

def tes_trailing_slsh 
    add_host! 
    options = {:controller => 'foo', :trailing_slash => true, :action => 'bar', :id => '33'} 
    assert_equal('http://www.basecamphq.com/foo/bar/33/', W.new.url_for(options)) 
end 

가장 좋은 방법은 Rack 또는 웹 서버를 사용하여 리디렉션을 실행하는 것입니다. 아파치에서 , 당신은 슬래쉬에 해당 하나에 후행 슬래시없이 모든 경로를 리디렉션하려면 같은

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

로 정의를 추가 할 수 있습니다.

또는 당신은 랙 수준에서 레일 응용 프로그램에서 동일한 작업을 수행 할 rack-rewrite를 사용할 수 있습니다.

+0

랙 재 흥미로운 옵션입니다. 가능하다면 웹 서버 측에서 추가 미들웨어를 사용하지 않고 Rails에서 솔루션을 선호합니다. –

+1

사실, 'redirect ("/ test /")를 호출하면 Rack 미들웨어를 사용하게됩니다. ;) –

0

어쩌면 그것이 내가 블로그에 대한 cannonical URL을 가지고 동일한 작업을 수행하고 싶어

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

아니요, 작동하지 않습니다. –

2

작동이는

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 

작동 i를 다루는 또 다른 규칙이 게시물 내의 상대 경로. 순서가 중요하므로 이전이 먼저 가고 일반는 두 번째가됩니다.

3

강제로 컨트롤러 수준에서 리디렉션 할 수 있습니다.

# 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 
+1

'original_url'에도 검색어 매개 변수가 포함되어 있으므로이 체크가 너무 많이 걸립니다. – cburgmer

관련 문제