nginx使用根据head请求头进行后端代理
需求
公司需要进行区分用户访问集群实现特定用户访问灰度集群、重要用户访问正式集群
从而保障正式集群稳定性
具体架构如下
实现
nginx 配置
打开nginx 配置文件
server {
listen *:80; # 监听80端口
server_name test.com; # 域名
index index.php index.html; # 默认访问文件
access_log logs/test.access.log main; # 访问日志
error_log logs/test.error.log notice; # 错误日志路径
root /data/test/;
charset utf-8;
location / {
if ($http_token = ‘’) { # 如果没有接收到请求头没有token 标签时 返回http code 400 表示访问失败
return 400
}
if ($http_token = 'zhenshi') { # 如果接收到请求头部 token: zhenshi 将请求转发到127.0.0.1:400 端口并转发请求头
proxy_pass http://127.0.0.1:400/;
proxy_set_header Host $http_host;
}
if ($http_token = 'huidu') { # 如果接收到请求头部 token: huidu 将请求转发到127.0.0.1:500 端口并转发请求头
proxy_pass http://127.0.0.1:500/;
proxy_set_header Host $http_host;
}
if ($http_token = 'yanshi' { # 用于下方演示
return 500
}
}
}
nginx 相关模块及配置推荐 nginx 中文网站学习
https://www.nginx.cn/doc/index.html
测试验证
- 需要在特定用户发送请求时添加特定http head头部
研发配合支持实现
python 实现方法
import requests
base_url = 'http://test.com'
form_data = {"user": "123", "pwd": '456'}
form_header = {"token": "huidu"} # 设置请求头,字典格式
r = requests.post(base_url + '/post', data=form_data, headers=form_header)
print(r.url) # 打印URL
print(r.status_code)
print(r.text)
curl 方法
curl -H "token:yanshi" -vvv test.com
演示curl 结果
* About to connect() to test.com port 80 (#0)
* Trying *.*.*.* ...
* Connected to test.com (*.*.*.*) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: test.com
> Accept: */*
> token:yanshi
>
< HTTP/1.1 500 Internal Server Error
< Server: nginx/1.14.2
< Date: Tue, 27 Apr 2021 02:37:36 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 193
< Connection: close
<
<html>
<head><title>500 Internal Server Error</title></head>
<body bgcolor="white">
<center><h1>500 Internal Server Error</h1></center>
<hr><center>nginx/1.14.2</center>
</body>
</html>
* Closing connection 0
返回 500 表示 成功