nginx使用proxy_pass分发,稍不注意会掉坑:
测试配置

    upstream tomcats {
        server 10.96.119.199:8080 weight=1;
    }

    server {
        server_name test.com;
        access_log api.log;

        location /api1 { 
            proxy_pass http://tomcats; 

            proxy_set_header Host host;
            proxy_set_header X-Real-IPremote_addr;
            proxy_set_header X-Forwarded-For proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protoscheme;
        }

        location /api2 { 
            proxy_pass http://tomcats/; 

            proxy_set_header Host host;
            proxy_set_header X-Real-IPremote_addr;
            proxy_set_header X-Forwarded-For proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protoscheme;
        }

        location /api3/ { 
            proxy_pass http://tomcats; 

            proxy_set_header Host host;
            proxy_set_header X-Real-IPremote_addr;
            proxy_set_header X-Forwarded-For proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protoscheme;
        }

        location /api4/ { 
            proxy_pass http://tomcats/; 

            proxy_set_header Host host;
            proxy_set_header X-Real-IPremote_addr;
            proxy_set_header X-Forwarded-For proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protoscheme;
        }

    }

日志情况

127.0.0.1 - - [01/Jun/2020:16:20:31 +0800] "GET /api1/pwd?len=15 HTTP/1.1" 404 140 "-" "curl/7.29.0"
127.0.0.1 - - [01/Jun/2020:16:21:10 +0800] "GET /api2/pwd?len=15 HTTP/1.1" 200 53 "-" "curl/7.29.0"
127.0.0.1 - - [01/Jun/2020:16:21:14 +0800] "GET /api3/pwd?len=15 HTTP/1.1" 404 140 "-" "curl/7.29.0"
127.0.0.1 - - [01/Jun/2020:16:21:21 +0800] "GET /api4/pwd?len=15 HTTP/1.1" 200 53 "-" "curl/7.29.0"

比对

locationurl结果
/http://10.96.119.199:8080/pwd?len=15{“password”:”UpXyC2bR9W_qwRV”,”length”:15}
api1http://test.com/api1/pwd?len=15{“timestamp”:”2020-06-01T07:36:13.492+0000″,”status”:404,”error”:”Not Found”,”message”:”No message available”,”path”:”/api1/pwd”}
api2http://test.com/api2/pwd?len=15{“password”:”UpXyC2bR9W_qwRV”,”length”:15}
api3http://test.com/api3/pwd?len=15{“timestamp”:”2020-06-01T07:37:34.938+0000″,”status”:404,”error”:”Not Found”,”message”:”No message available”,”path”:”/api3/pwd”}
api4http://test.com/api4/pwd?len=15{“password”:”UpXyC2bR9W_qwRV”,”length”:15}

结论
– 当locationproxy_pass同时带或者同时不带斜杠时,uri部分不修改,直接传到proxy_pass的后端
– 当locationproxy_pass一个带一个不带斜杠时候,匹配的uri部分将会被修改为该参数中的uri,造成后端无法识别。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code