nginx使用根据请求头进行后端代理

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

测试验证

  1. 需要在特定用户发送请求时添加特定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 表示 成功

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值