I'd try and do this at Nginx level, failing that Rack::Rewrite maybe?