James Crisp

Software dev, tech, mind hacks and the occasional personal bit

Fixing ‘Invalid query parameters: invalid %-encoding’ in a Rails App

Sometimes users manually edit query strings in the address bar, and make requests that have invalid encodings. Unfortunately Rails does not handle this neatly and the exception bubbles up. Eg,

ActionView::Template::Error: Invalid query parameters: invalid %-encoding (%2Fsearch%2Fall%Forder%3Ddescending%26page%3D5%26sort%3Dcreated_at)

/rack/lib/rack/utils.rb:127:in `rescue in parse_nested_query'

[Note: This was with Passenger, which passed the request through to the app – your mileage may vary with other servers]

In the case of my app, these corrupted query strings are not that important, but users are receiving 500 server error pages. Sometimes they end up with a bad query string URL cached in browser history, so they keep going back to it rather than to the home page.

A simple solution, that gives a good user experience for my app, is to simply drop the query string on a request completely if it has invalid encoding. See my implementation using Rack middleware below:


Doing a Website Re-design or new look


“The Magic of Thinking Big” by David Schwartz


  1. Giedrius


    Thanks for the post. Do you include this middleware anywhere among others or is it important to have it before any or after any other middleware?

  2. James

    Hi Giedrius

    I added it before Rack::Runtime, like so:

    config.middleware.insert_before Rack::Runtime, HandleBadEncodingMiddleware

    so the bad encoding wouldn’t get to Rack middleware.


Leave a Reply

Powered by WordPress & Theme by Anders Norén