Redirect to canonical route in without trailing slash in Rails 3

前端 未结 4 1513
你的背包
你的背包 2021-01-19 15:46

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/\"         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-19 16:04

    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
    

提交回复
热议问题