URI::InvalidURIError (URI must be ascii only)

后端 未结 1 1527
耶瑟儿~
耶瑟儿~ 2021-01-23 06:23

I have a legacy rails 3.2 app, when I try to hit a route with a none-ascii char e.g; example.com/city/bergstraße then I get the following error:

/Us         


        
相关标签:
1条回答
  • 2021-01-23 07:01

    According to RFC 3986 a URI may contain only a subset of ASCII characters.

    To provide a valid URI the non-ASCII characters should be escaped:

    irb(main):008:0> URI.parse "example.com/city/#{URI.encode('bergstraße')}"
    => #<URI::Generic example.com/city/bergstra%C3%9Fe>
    

    The problem is, that I get this error before hitting any controller, so I just wonder where can I catch this error to parse and fix the URL?

    The problem is you should not really be catching this error. Your rails server should not be responsible for responding to bad or malformed requests.

    While you could attempt to write a piece of middleware to hack around the issue you should instead figure out why the clients are sending requests for an invalid URI.

    If they are originating from your own application make sure you are escaping slug columns properly and not just creating urls with string interpolation. The stringex gem or friendly_id are your friends here.

    0 讨论(0)
提交回复
热议问题