Nginx 405方法不允许,即使有JSON响应

时间:2019-10-17 21:19:28

标签: nginx nginx-location

我的nginx看起来像

error_page 401 @json401;
location @json401 {
  try_files /errors/401.json;
  internal;
}

我的errors/401.json看起来像

{
  "status": 401,
  "error": "Authorization required.",
  "detail": "Please log in first before accessing this page."
}

我知道nginx无法为非GET请求返回静态页面,但是我正在尝试返回JSON。

现在,当我向具有401响应的端点发出POST请求时,我仍然收到405 Method Not Allowed(GET请求正确返回JSON文件)。我还尝试添加default_type application/json,但仍然得到405。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

https://nginx.org/en/docs/http/ngx_http_core_module.html#error_page

  

如果在内部重定向期间无需更改URI和方法,则可以将错误处理传递到指定位置:

因此,当您使用命名位置时,它会使用与原始位置(POST)相同的方法,并且try_files仅接受GET方法,因此得到405。

您应使用常规(未命名)位置,因为在这种情况下,任何方法都将被GET取代:

  

这将导致内部重定向到指定的uri ,并且客户端请求方法已更改为“ GET”(对于“ GET”和“ HEAD”以外的所有方法)

以下示例按预期工作:

error_page 401 /json401;

location /json401 {
  internal;
  default_type application/json;
  try_files /errors/401.json =401;
}

location = /test {
  return 401;
}
$ curl -X POST http://localhost:9999/test -sD - 

HTTP/1.1 401 Unauthorized
...
Content-Type: application/json
Content-Length: 120
Connection: close
...

{
  "status": 401,
  "error": "Authorization required.",
  "detail": "Please log in first before accessing this page."
}
相关问题