TL;DR

80或者443的 nginx 增加

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
location / {
        proxy_pass http://127.0.0.1:8612/;
        add_header Access-Control-Allow-Methods *;
        add_header Access-Control-Max-Age 3600;
        add_header Access-Control-Allow-Origin $http_origin;
        add_header Access-Control-Allow-Credentials true;
        proxy_set_header Host            $host;
        proxy_set_header X-Forwarded-Proto $scheme; #要透传的协议
        proxy_set_header X-Forwarded-Port $server_port; #要透传的接口
        if ($request_method = OPTIONS){
            return 200;
        }
    }

第二层 nginx 增加

1
2
3
4
5
location / {
        proxy_pass http://127.0.0.1:8611/;
        proxy_set_header X-Forwarded-Port $http_x_forwarded_port;
        proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
    }

代码中获取协议的地方改成从 header 中获取X-Forwarded-Port

1
retRequest.getHeader("X-Forwarded-Port")

为什么有这个需求

公司的正常的 nginx 前边挂了另外一个 nginx (SLB)做接入,正好赶上8611这个落地的 java 需要判断当前请求是 http 还是 https 来做不同的处理,多了一层 SLB 之后造成代码中通过request.getServerPort()获取端口号时候一直获取的是80端口