Skip to content

Instantly share code, notes, and snippets.

@gwire
Last active June 14, 2023 21:19
Show Gist options
  • Save gwire/02452d28b9c9079619aca22b8ccbdee8 to your computer and use it in GitHub Desktop.
Save gwire/02452d28b9c9079619aca22b8ccbdee8 to your computer and use it in GitHub Desktop.
Generating 405 responses in nginx

I have a site where there is no legitmate use of the HTTP POST method (or anything other than GET/HEAD).

limit_except is usually used for method restriction, but only produces 403 responses, not 405. There's a Stack Overflow question that notes this. There's a 2015 blog post that suggests something like the following (which I needed to modify to get the Allow: header to appear):

server {
  ### regular config

  location @error405 {
    add_header Allow "GET, HEAD" always;
    return 405;
  }
  error_page 405 @error405;
        
  location / {
    if ( $request_method !~ ^(GET|HEAD)$ ) {
      return 405;
    }
    
    ### regular config
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment