在Rails 3中重定向到规范路由而不会出现斜线 [英] Redirect to canonical route in without trailing slash in Rails 3

查看:65
本文介绍了在Rails 3中重定向到规范路由而不会出现斜线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails 3上,我试图从没有尾部斜杠的URL重定向到具有斜杠的规范URL。

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

但是,上述路由同时匹配/ test和/ 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?

推荐答案

您可以在控制器级别强制重定向。

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

这篇关于在Rails 3中重定向到规范路由而不会出现斜线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆