测试环境

nginx 服务器 IP:192.168.4.20
web 服务器IP:192.168.4.5

配置详情

1. 在 web 服务器(192.168.4.5)上启动简易 Flask 服务来获取Host 信息。编辑req.py:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/')
def getrequest():
    useragent=request.headers.get('Host')

    return useragent

if __name__ == '__main__':
    app.run(host="0.0.0.0",port="9000")

启动脚本:

[root@localhost ~]# python3 req.py 
 * Serving Flask app 'req' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://192.168.4.5:9000/ (Press CTRL+C to quit)
192.168.4.20 - - [03/Sep/2021 15:36:33] "GET / HTTP/1.1" 200 -

表示可以监听192.168.4.5 的 9000 端口

2. 在 nginx 服务器(192.168.4.20)上配置:

2.1 配置不添加 proxy_set_header Host
upstream test{
   server 192.168.4.5:9000;
}

server {
    listen 80;
    server_name _;

    location / {
        proxy_pass http://test;
    }
}

在不添加proxy_set_header Host $host 的时候进行测试:

[root@localhost ~]# curl http://192.168.4.20
test

返回的结果是test。web后端获取得到的是一个 upstream 虚拟主机名字

2.2 配置添加 proxy_set_header Host
upstream test{
   server 192.168.4.5:9000;
}

server {
    listen 80;
    server_name _;

    location / {
        proxy_set_header Host    $host;
        proxy_pass http://test;
    }
}

测试结果如下:

[root@localhost ~]# curl http://192.168.4.20
192.168.4.20

web后端获取得到web代理服务器的host。