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

问题描述 投票:0回答:1

我的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。

感谢您的帮助。

nginx nginx-location
1个回答
0
投票

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."
}
© www.soinside.com 2019 - 2024. All rights reserved.