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

Nginx 405 Method Not Allowed, even with JSON response

我的 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 不能 return 非 GET 请求的静态页面,但我正在尝试 return JSON。

现在,当我向具有 401 响应的端点发出 POST 请求时,我仍然收到 405 方法不允许(GET 请求正确 return JSON 文件) .我也尝试添加 default_type application/json 但仍然得到 405.

感谢帮助。

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

If there is no need to change URI and method during internal redirection it is possible to pass error processing into a named location:

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

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

This causes an internal redirect to the specified uri with the client request method changed to “GET” (for all methods other than “GET” and “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."
}