![](/img/trans.png)
[英]Returns 400 Bad Request by POST, PUT methods but GET is working okay
[英]troubleshooting application behind nginx reverse proxy, as POST/PUT requests are replied with Error 400 (Bad Request)
我第一次尝试在 linux 上托管我的 Angular/ASP.net core 3.1 应用程序。
Nginx 位于端口 80 上,为 static 文件提供服务,并充当 api 部分的反向代理,该部分将传递给 .NET/kestrel 服务器。
问题是我在任何包含正文的 web API 请求中系统地收到 400 状态代码错误(错误请求),例如 POST 和 PUT,但 GET 可以。
我通过中间件添加了一些日志,只是为了看看我是否可以获得请求。 基本上,类似:
app.Use(async (context, next) => {
context.Request.EnableBuffering();
string reqBody;
using (var reader = new StreamReader(context.Request.Body))
{
reqBody = await reader.ReadToEndAsync();
context.Request.Body.Seek(0, SeekOrigin.Begin);
ms_oLogger.Debug($"Incoming request: METHOD={context.Request.Method} PATH={context.Request.Path} BODY=\"{reqBody}\"");
}
await next();
});
这只是为 GET 请求记录内容,但对于有问题的 PUT/POST 请求没有任何显示...我可以得出结论,这只是一个 nginx 问题吗?
我还为给定的“/api”位置启用了 nginx 上的日志,但我不知道会发生什么……我怎么知道哪一层生成了 400 状态代码?
EDIT1:我开始了一个空白的新项目,只是用一个糟糕的 Web API 项目包含一个 GET 和一个 POST 方法,只是为了检查我的应用程序是否有问题,但我仍然遇到问题。 所以我设置了一个新的 ubuntu 服务器(这次是 ubuntu 服务器而不是桌面版本),现在它可以工作了......我比较了配置等......但不知道出了什么问题。:?.. 但我最初的问题仍然有效:如何解决问题的根源?
EDIT2:这是我的 default.conf:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
location /fusion {
root /opt/fichet/WebUI/NgApp;
}
location /fusion/api {
proxy_pass http://localhost:5000/api;
error_log /var/log/nginx/fusion_error_logs.log debug;
access_log /var/log/nginx/fusion_access.log;
proxy_http_version 1.1;
proxy_cache_bypass $http_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
}
}
似乎没有启用防火墙(“sudo ufw status verbose”告诉我们它是“不活动的”)
从 nginx 配置中删除这些行。
proxy_cache_bypass $http_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
这些标头用于 WebSocket 连接,不应出现在非 websocket 请求中。 我的猜测是,出于某种原因,您的上游服务器不介意 GET 请求,但不介意 POST/PUT。
如果您不使用 websockets,您可以将它们移除。
如果您使用的是 websockets,则需要 nginx 根据请求是否为 websockets 添加或不添加这些标头。 像这样的东西应该工作:
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
...
location /fusion/api {
proxy_pass ...
...
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
请参阅此处了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.