nginx 代理post請求做負載均衡


項目中遇到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就不會重定向了!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM