Details of Sinatra’s Redirect Helper
A question came up on IRC today regarding Sinatra’s redirect helper. royfreeman was trying to redirect from inside a post action. Sinatra redirected the URL ok, but the new request continued to use the POST method to request the new URL. He was trying to do this from a mobile device, and was confused when the request used a GET with his laptop’s browser.
Sinatra sends a 302 response code as a redirect. According to the spec, 302 shouldn’t change the request method, but you can see a note saying that most clients do change it. Apparently the mobile browser that person was using did things correctly (instead of the mainstream misinterpretation).
The fix for this in the spec is 2 different response codes: 303 and 307. 303 resets to GET, 307 keeps the same method.
To force sinatra to send a different response code, it’s very simple:
redirect '/', 303 # forces the 303 return code
## OR:
redirect '/', 307 # forces the 307 return code
Many thanks to Sydd for working through this, he did most of the hunting to find the specification details and to figure out what was going on.
Leave a Reply