Skip to content

Instantly share code, notes, and snippets.

@remvee
Created September 28, 2010 07:39
Show Gist options
  • Save remvee/600569 to your computer and use it in GitHub Desktop.
Save remvee/600569 to your computer and use it in GitHub Desktop.
silence ActionController::UnknownHttpMethod exceptions
# Avoid annoying ActionController::UnknownHttpMethod exceptions like:
#
# ActionController::UnknownHttpMethod) "CONNECT, accepted HTTP methods are get, head, put, post, delete, and options"
#
# Install this file in app/metal and these requests will receive a 405
# "Method Not Allowed" status and will be logged under `info'.
class IgnoreUnknownHttpMethod
def self.call(env)
[
if ActionController::Request::HTTP_METHODS.include?(env["REQUEST_METHOD"].downcase)
404 # Not Found
else
Rails.logger.info("Ignoring unknown HTTP method; #{env.inspect}")
405 # Method Not Allowed
end, {"Content-Type" => "text/plain"}, []]
end
end
@shamil614
Copy link

Hey great snippet! Thanks for contributing. I was wondering if you could help me understand something. I know it works but I don't understand why. I understand how the ELSE section returns 405, but why doesn't the IF clause return 404 for GET, POST, etc? To me the IF reads: return 404 status code if HTTP_METHODS are either GET, POST, PUT, etc.

@remvee
Copy link
Author

remvee commented May 25, 2011

Returning 404 (not found) says "I don't known what to do with this" and the next handler is called, in most cases the rails dispatcher. A lot of deployment setups work in the same way: apache first tries to serve a file from the application public directory, when that fails (nothing found) it gives the request to rails.

@shamil614
Copy link

Ahhhh....that makes sense. Thanks for the sharing!

@mpoisot
Copy link

mpoisot commented Mar 7, 2013

How would you get this to work on Rails3?

@jturkel
Copy link

jturkel commented Jun 20, 2014

It looks like you can modify Rails' exception to http status code mapping (at least in Rails 3.2) to do this:

 ActionDispatch::ExceptionWrapper.rescue_responses.merge!(
      'ActionController::UnknownHttpMethod' => :method_not_allowed)

It looks like this entry is in the map by default in Rails 4 so things should work out of the box there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment