使用Nginx将PATCH请求代理到POST
我尝试使用nginx将HTTP PATCH请求重定向到HTTP POST请求.
I tried to redirect HTTP PATCH request to HTTP POST request with nginx.
我也尝试了以下配置,但是它不起作用(我收到了400个错误的请求):
I also tried the following configuration but it's not working (I got 400 bad request):
http {
map $request_method $my_method {
default $request_method;
PATCH "POST";
}
server {
location /api {
proxy_method $my_method;
proxy_pass http://localhost:8080/api;
}
}
}
显然,指令"proxy_method $my_method
"不起作用.也许我的地图指令不正确,但我真的不明白为什么.
Apparently, the directive "proxy_method $my_method
" is not working. Maybe my map directive is not OK but I really don't understand why.
我也尝试设置一个变量,例如以下示例,但结果相同 http {
I also try to set a variable like the following exemple but with the same result http {
server {
location /api {
set $my_method $request_method;
if($request_method = PATCH){
set $my_method POST;
}
proxy_method $my_method;
proxy_pass http://localhost:8080/api;
}
}
}
显然,proxy_method无法有效地使用变量.您可以尝试改用旧的goto技巧:
Apparently, proxy_method cannot currenly work with variables. You could try and use the good old goto trick instead:
location / {
error_page 418 = @patch;
if ($request_method = "PATCH") {
return 418;
}
proxy_pass http://localhost:8080;
}
location @patch {
proxy_method POST;
proxy_pass http://localhost:8080;
}
如果没有指定位置,那么您可以随时使用另一个goto技巧:
If a named location is not an option, then you can always use another goto trick:
location /api {
if ($request_method = "PATCH") {
rewrite ^/api(.*)$ /internal$1 last;
}
proxy_pass http://localhost:8080/api;
}
location /internal/ {
internal;
rewrite ^/internal/(.*)$ /$1 break;
proxy_method POST;
proxy_pass http://localhost:8080/api;
}
顺便说一句,在您的示例中,没有必要将/api添加到proxy_pass,因为它与位置匹配.删除此部分不会改变将请求代理到后端的方式.
Incidentally, in your example there is no point in adding /api to proxy_pass, since it matches the location. Removing this part will not change anything in the way the request is proxied to the backend.