在 Rails 的 routes.rb 中匹配带有斜杠的 URL [英] Matching URLs with a trailing slash in Rails' routes.rb

查看:31
本文介绍了在 Rails 的 routes.rb 中匹配带有斜杠的 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法根据请求 URL 是否有斜杠在 Rails 的 routes.rb 中执行不同的路由?这似乎很困难,因为请求对象的尾部斜杠已被删除,这意味着 http://www.example.com 的 GET/about/ 的 request.url 值为 http://www.example.com/about.该行为阻止使用 基于请求的约束 以及 route-globbing.

Is there a way to perform different routing in Rails' routes.rb depending on whether the request URL has a trailing slash? This seems difficult since the request object has its trailing slash removed, meaning a GET of http://www.example.com/about/ has a request.url value of http://www.example.com/about. That behavior prevents matching using request-based constraints as well as route-globbing.

推荐答案

我发现的一个解决方案是使用 request.env["REQUEST_URI"],它包含随请求提交的原始 URL.不幸的是,由于它不是请求的直接字符串属性,它需要一个自定义匹配对象:

One solution I've found is to use request.env["REQUEST_URI"], which contains the raw URL submitted with the request. Unfortunately, since it's not a direct string property of the request, it requires a custom matching object:

class TrailingSlashMatcher
  def matches?(request)
    uri = request.env["REQUEST_URI"]
    !!uri && uri.end_with?("/")
  end
end

AppName::Application.routes.draw do
  match '/example/*path', constraints: TrailingSlashMatcher.new, to: redirect("/somewhere/")
end

这似乎有点矫枉过正,所以希望有人有更优雅的方法.

That seems like overkill, so hopefully someone has a more elegant approach.

这篇关于在 Rails 的 routes.rb 中匹配带有斜杠的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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