Redirect to canonical route in without trailing slash in Rails 3

前端 未结 4 1558
你的背包
你的背包 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

    There is an option in ActionDispatch called trailing_slash you can use to force the trailing slash at the end of the URL. I'm not sure if it can be used in the routing definition.

    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
    

    In your case, the best way is to use Rack or your web server to execute the redirect. In Apache, you can add a definition such as

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

    To redirect all routes without a trailing slash to the corresponding one with trailing slash.

    Or you can use rack-rewrite to perform the same task in your Rails app at Rack level.

提交回复
热议问题