简体   繁体   English

在Rails 3中允许编码斜杠在URL段中的最佳方法是什么?

[英]What's the best way of allowing encoded slashes in a URL segment in Rails 3?

What I want 我想要的是

I want to pass a URL segment with an encoded slash. 我想传递带有编码斜杠的URL段。


The Problem 问题

  • Running locally on Thin, it works 在Thin上本地运行,它可以工作
  • Running on the server on Passenger/Nginx/Rack, it breaks 在Passenger / Nginx / Rack上的服务器上运行,它会中断
  • Something decodes the slash before it reaches Rails 在到达Rails之前,有些东西会对斜杠进行解码

My Question 我的问题

  • What's the best way of allowing parameters to have slashes? 允许参数有斜杠的最佳方法是什么?

What I've Tried 我试过的


The Detail 细节

routes.rb 的routes.rb

get '/api/shops/:city', to: 'shops#index', constraints: /[0-9A-Za-z\-\.\%\s]+/

Form 形成

The user can select their area from a dropdown: 用户可以从下拉列表中选择他们的区域:

London/Dover
Glasgow/Edinburgh

On Submit 提交

We hit the API with: /api/shops/London%2FDover 我们点击了API: /api/shops/London%2FDover

We encode the slash when building the url for obvious reasons. 出于显而易见的原因,我们在构建url时对斜杠进行编码。

This works... 这有效......

Running locally on Rails on Thin. 在瘦上的Rails上本地运行。

The URL is recognised by the routes, the slash is decoded inside Rails and inside our application we have London/Dover as a parameter. URL被路由识别,斜杠在Rails中解码,在我们的应用程序中,我们将London / Dover作为参数。

This breaks... 这打破了......

Running on the server on Nginx, Passenger and Rack. 在Nginx,Passenger和Rack上运行在服务器上。

The slash is decoded before it hits Rails. 斜杠在它击中Rails之前被解码。

/api/shops/London/Dover isn't a route so responds with a 404. /api/shops/London/Dover不是一条路线,所以回复404。

Versions 版本

  • Passenger 3.0.2 乘客3.0.2
  • Nginx 1.2.9 Nginx 1.2.9
  • Rack 1.2 (Release 1.5) Rack 1.2(1.5版)
  • Rails 3.2.17 Rails 3.2.17

We faced the same problem. 我们遇到了同样的问题。 We tried encoding the string using CGI::escape , URI::encode, ERB::Util::url_encode, but nothing worked on server with passenger and nginx. 我们尝试使用CGI :: escape,URI :: encode,ERB :: Util :: url_encode对字符串进行编码,但是在带有passenger和nginx的服务器上没有任何工作。 The solution that worked for us was to modify the route to use wild card character, known as "Route Globbing". 对我们有用的解决方案是修改使用外卡字符的路由,称为“Route Globbing”。 Refer this link : http://guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments 请参阅此链接: http//guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments

So, in your case, the route becomes 所以,在你的情况下,路线成为

`get '/api/shops/*city', to: 'shops#index', constraints: /[0-9A-Za-z\-\.\%\s]+/ `

instead of get '/api/shops/:city', to: 'shops#index', constraints: /[0-9A-Za-z\\-\\.\\%\\s]+/ . 而不是get '/api/shops/:city', to: 'shops#index', constraints: /[0-9A-Za-z\\-\\.\\%\\s]+/

Notice the wild card character in the route before parameter "city". 注意参数“city”之前的路径中的通配符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM