How to make sure mongrel will handle bad HTTP requests (or how to avoid 502 errors)

November 4th, 2008

If you’re using (Apache2, mongrel and mod_proxy) for your Rails application you might have realized that when a bad HTTP request is performed over your app, mongrel triggers an exception :

$ mar nov 04 14:45:44 +0000 2008: HTTP parse error, malformed request (127.0.0.1): #

At first glance, this could sound logical that mongrel refuses to serve an invalid request, but if you’re a service provider, your first rule is: Never give up on anything. Rememeber : you’re on the Internet, you will have some junk in the hands eventually.

So, as a service provider, you wan’t your web application to be as pragmatic as possible: if an invalid request comes into play, let’s try to sanitize it so it can fallback to something understandable by mongrel.

This specific issue happen when you want to access a Rails app with an invalid/incomplete URL-encoded string in the query string, for instance :

var=%ZZ

The following RewriteRule Voodoo replace any invalid % snippets with their encoded form (%25):

RewriteCond %{QUERY_STRING} (.*)%([^0-9a-fA-F]|[0-9a-fA-F][^0-9a-fA-F]|$)(.*)
RewriteRule (.*) $1?%1\%25%2%3 [N]
  1. No comments yet.
  1. No trackbacks yet.