1、瀏覽器直接訪問服務(wù),獲取到的 Host 包含瀏覽器請求的 IP 和端口
# cat ngx_header.py
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/')
def get_host():
host = request.headers.get('Host')
return jsonify({'Host': host}), 200
if __name__ == '__main__':
app.run(host='10.1.200.107', port=5000)
# python ngx_header.py
結(jié)果如下:
2、配置 nginx 代理服務(wù)后
2.1 不設(shè)置 proxy_set_header Host 時,瀏覽器直接訪問 nginx,獲取到的 Host 是 proxy_pass 后面的值忌怎,即 $proxy_host 的值,參考 http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header
# cat ngx_header.conf
server {
listen 8090;
server_name _;
location / {
proxy_pass http://10.1.200.107:5000;
}
}
結(jié)果如下:
2.2 設(shè)置 proxy_set_header Host $host 時酪夷,瀏覽器直接訪問 nginx榴啸,獲取到的 Host 是 $host 的值,沒有端口信息
# cat ngx_header.conf
server {
listen 8090;
server_name _;
location / {
proxy_set_header Host $host;
proxy_pass http://10.1.200.107:5000;
}
}
結(jié)果如下:
2.3 設(shè)置 proxy_set_header Host $host:$proxy_port 時晚岭,瀏覽器直接訪問 nginx鸥印,獲取到的 Host 是 $host:$proxy_port 的值
# cat ngx_header.conf
server {
listen 8090;
server_name _;
location / {
proxy_set_header Host $host:$proxy_port;
proxy_pass http://10.1.200.107:5000;
}
}
結(jié)果如下:
2.4 設(shè)置 proxy_set_header Host $http_host 時,瀏覽器直接訪問 nginx坦报,獲取到的 Host 包含瀏覽器請求的 IP 和端口
server {
listen 8090;
server_name _;
location / {
proxy_set_header Host $http_host;
proxy_pass http://10.1.200.107:5000;
}
}
結(jié)果如下:
2.5 設(shè)置 proxy_set_header Host $host 時库说,瀏覽器直接訪問 nginx,獲取到的 Host 是 $host 的值片择,沒有端口信息潜的。此時代碼中如果有重定向路由,那么重定向時就會丟失端口信息字管,導(dǎo)致 404
# tree .
.
├── ngx_header.py
└── templates
├── bar.html
└── foo.html
1 directory, 3 files
// ngx_header.py 代碼
# cat ngx_header.py
from flask import Flask, request, render_template, redirect
app = Flask(__name__)
@app.route('/')
def get_header():
host = request.headers.get('Host')
return render_template('foo.html',Host=host)
@app.route('/bar')
def get_header2():
host = request.headers.get('Host')
return render_template('bar.html',Host=host)
@app.route('/2bar')
def get_header3():
# 代碼層實現(xiàn)的重定向
return redirect('/bar')
if __name__ == '__main__':
app.run(host='10.1.200.107', port=5000)
// foo.html 代碼
# cat templates/foo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>foo</title>
</head>
<body>
Host: {{ Host }}
</br>
<a href="2bar"">頁面跳轉(zhuǎn)</a>
</body>
</html>
// bar.html 代碼
# cat templates/bar.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>bar</title>
</head>
<body>
Host: {{ Host }}
</body>
</html>
# python ngx_header.py
# cat ngx_header.conf
server {
listen 8090;
server_name _;
location / {
proxy_set_header Host $host;
proxy_pass http://10.1.200.107:5000;
}
}
結(jié)果如下: