项目中遇到nginx代理post请求nodejs服务。但是一直404.发现好像是nginx重定向的时候将post请求变成了get请求。上配置:

# 负载均衡服务器配置
upstream pdf_upstream{
        server localhost:3000;
        server localhost:3001; } #代理配置 location ^~ /post/{ proxy_pass http://post_upstream; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
上面的配置测试一直无法通过。网上的rewrite方法我试了一下,好像也不行(对rewrite不是很了解,照葫芦画瓢发现不行)。最后加上proxy_method POST;这个配置,使用测试工具可以正常测试。但是这样配置有2个问题:
  • 如果服务器有get请求的同名url,可能导致get无法被代理.
  • Nginx还是会继续重定向。
问题1尚不知道怎么解决。只能不提供get同名接口。
问题2的出现,在使用过httpClient的时候,需要我们处理重定向问题:
private CloseableHttpResponse redirect(CloseableHttpClient httpClient, StringEntity entity, CloseableHttpResponse response, int statusCode) throws IOException {
        HttpPost post;
        if(statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_MOVED_PERMANENTLY){
            Header location = response.getFirstHeader("location"); String newUrl = location.getValue(); post = new HttpPost(newUrl); post.setEntity(entity); response = httpClient.execute(post); } return response; }

问题已解决!

为了解决nginx 总是post重定向get请求,打开nginx的说明文档 https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/,按照上面操作一步一步实现下去,发现post请求可以正常请求。

upstream backend {
        server localhost:8080;
        server localhost:3001; } server { location /post{ proxy_pass http://backend; } location / { proxy_pass http://backend; } }
比对上面的配置和之前的配置,发现只有匹配的表达式不同。结果问题真的出现在这里!!

做匹配路由的时候,最后不要跟 / 

这样nginx就不会重定向了!