Proxying PATCH request to POST with nginx

2019-04-16 04:31发布

I tried to redirect HTTP PATCH request to HTTP POST request with nginx.

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;            
        }             
    }
}

Apparently, the directive "proxy_method $my_method" is not working. Maybe my map directive is not OK but I really don't understand why.

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;            
        }             
    }
}

标签: nginx
1条回答
虎瘦雄心在
2楼-- · 2019-04-16 05:10

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;
}

EDIT:

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;
}

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.

查看更多
登录 后发表回答