nginx通过自定义header属性来转发不同的服务

一、背景

因为需要上线灰度发布,只要nginx接收到头部为:

wx_unionid:123456

 

就会跳转到另外一个url,比如:

127.0.0.1:8080

 

通过配置nginx 匹配请求头wx_unionid 来转发到灰度环境。
核心:客户端自定义的http header,在nginx的配置文件里能直接读取到。
条件:header必须用减号“-”分隔单词,nginx里面会转换为对应的下划线“_”连接的小写单词。

 

二、修改Nginx配置

安装nginx

apt-get install -y nginx

 

编辑主页

cd /etc/nginx/sites-enabled
vim home.conf

内容如下:

upstream wx {
    server 127.0.0.1:8080;
}

server {  
    listen 8008;
    server_name localhost;

    root html;
    index index.html;

    charset utf-8;
    underscores_in_headers on;
    location / {
        #测试header转发 
        if ($http_wx_unionid = "123456") {
            proxy_pass http://wx;
        }  
    }  
} 

参数配置说明

underscores_in_headers on:nginx是支持读取非nginx标准的用户自定义header的,但是需要在http或者server下开启header的下划线支持:
比如我们自定义header为wx_unionid,获取该header时需要这样:$http_wx_unionid(一律采用小写,而且前面多了个http_)


如果需要把自定义header传递到下一个nginx:
1.如果是在nginx中自定义采用proxy_set_header X_CUSTOM_HEADER $http_host;
2.如果是在用户请求时自定义的header,例如curl –head -H “X_CUSTOM_HEADER: foo” http://domain.com/api/test,则需要通过proxy_pass_header X_CUSTOM_HEADER来传递

编辑调整页

vim wx.conf

内容如下:

server {
    listen 8080;
    server_name localhost;

    root /var/www/html;
    index wx.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

 

增加测试页面

vim /var/www/html/wx.html

内容如下:

<h1>微信小程序测试平台</h1>

 

三、测试结果

加自定义头部

root@ubuntu:~# curl -v -H 'wx_unionid:123456' 127.0.0.1:8008
* Rebuilt URL to: 127.0.0.1:8008/
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 8008 (#0)
> GET / HTTP/1.1
> Host: 127.0.0.1:8008
> User-Agent: curl/7.47.0
> Accept: */*
> wx_unionid:123456
> 
< HTTP/1.1 200 OK
< Server: nginx/1.10.3 (Ubuntu)
< Date: Mon, 29 Jul 2019 07:49:46 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 37
< Connection: keep-alive
< Last-Modified: Mon, 29 Jul 2019 06:23:49 GMT
< ETag: "5d3e90f5-25"
< Accept-Ranges: bytes
< 
<h1>微信小程序测试平台</h1>
* Connection #0 to host 127.0.0.1 left intact

 

不加头部

root@ubuntu:~# curl -v 127.0.0.1:8008
* Rebuilt URL to: 127.0.0.1:8008/
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 8008 (#0)
> GET / HTTP/1.1
> Host: 127.0.0.1:8008
> User-Agent: curl/7.47.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: nginx/1.10.3 (Ubuntu)
< Date: Mon, 29 Jul 2019 07:50:13 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 612
< Last-Modified: Tue, 31 Jan 2017 15:01:11 GMT
< Connection: keep-alive
< ETag: "5890a6b7-264"
< Accept-Ranges: bytes
< 
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
* Connection #0 to host 127.0.0.1 left intact

 

四、匹配多条件

现在又多了一个需求,需要对客户端ip为:192.168.0.45,同时也增加自定义头部wx_unionid:123456,才会转发,否则不做转发。

 

nginx的配置中不支持if条件的逻辑与&& 逻辑或|| 运算 ,而且不支持if的嵌套语法,否则会报下面的错误:nginx: [emerg] invalid condition。

我们可以用变量的方式来间接实现。

要实现的语句:

if ($remote_addr ~* "192.168.0.45" && $http_wx_unionid = "123456"){
    proxy_pass http://wx;
}

 

如果按照这样来配置,就会报nginx: [emerg] invalid condition错误。

如下:

nginx: [emerg] invalid condition "$http_wx_unionid" in /etc/nginx/sites-enabled/home.conf:16
nginx: configuration file /etc/nginx/nginx.conf test failed

 

可以这么来实现,如下所示:

upstream wx {
    server 127.0.0.1:8080;
}

server {  
    listen 8008;
    server_name localhost;

    root html;
    index index.html;

    charset utf-8;
    underscores_in_headers on;
    location / {
        #测试header转发
        # 标志位
        set $flag 0;
        if ($remote_addr ~* "192.168.0.45"){
             # 末尾追加1,此时$flag=01
             set $flag "${flag}1";
        }
        if ($http_wx_unionid = "123456"){
            # 末尾追加1,此时$flag=011
            set $flag "${flag}1";
        }
        # 当为011时,表示条件都匹配
        if ($flag = "011") {
            proxy_pass http://wx;
        }
    }  
} 

 

重新加载配置

nginx -s reload

 

再次使用本机测试,增加头部

root@ubuntu:~# curl -v -H 'wx_unionid:123456' 127.0.0.1:8008
* Rebuilt URL to: 127.0.0.1:8008/
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 8008 (#0)
> GET / HTTP/1.1
> Host: 127.0.0.1:8008
> User-Agent: curl/7.47.0
> Accept: */*
> wx_unionid:123456
> 
< HTTP/1.1 200 OK
< Server: nginx/1.10.3 (Ubuntu)
< Date: Mon, 29 Jul 2019 08:01:30 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 612
< Last-Modified: Tue, 31 Jan 2017 15:01:11 GMT
< Connection: keep-alive
< ETag: "5890a6b7-264"
< Accept-Ranges: bytes
< 
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
* Connection #0 to host 127.0.0.1 left intact

 

登录到192.168.0.45,增加头部测试

root@docker-reg:~# curl -v -H 'wx_unionid:123456' 192.168.0.162:8008
* Rebuilt URL to: 192.168.0.162:8008/
*   Trying 192.168.0.162...
* Connected to 192.168.0.162 (192.168.0.162) port 8008 (#0)
> GET / HTTP/1.1
> Host: 192.168.0.162:8008
> User-Agent: curl/7.47.0
> Accept: */*
> wx_unionid:123456
> 
< HTTP/1.1 200 OK
< Server: nginx/1.10.3 (Ubuntu)
< Date: Mon, 29 Jul 2019 08:02:01 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 37
< Connection: keep-alive
< Last-Modified: Mon, 29 Jul 2019 06:23:49 GMT
< ETag: "5d3e90f5-25"
< Accept-Ranges: bytes
< 
<h1>微信小程序测试平台</h1>
* Connection #0 to host 192.168.0.162 left intact

 

 

 本文参考链接:

https://blog.youkuaiyun.com/qq_25934401/article/details/83113520

https://blog.youkuaiyun.com/lai0yuan/article/details/80784058

https://blog.youkuaiyun.com/woshizhangliang999/article/details/51701327

 



 

### Nginx 配置代理转发 参数详解 #### 基本概念与配置方式 Nginx作为反向代理服务器,能够有效地将客户端请求转发给后端的服务实例,并返回响应结果给客户端。对于常见的代理转发场景,可以通过`proxy_pass`指令来指定目标地址[^1]。 ```nginx server { listen 80; server_name example.com; location /api/ { proxy_pass http://backend_server/; # 更多配置项... } } ``` #### 转发参数设置 为了优化性能并确保正确处理HTTP头信息,在实际部署中通常会加入一系列辅助性的配置选项: - **修改Host头部字段** 当需要让被代理的应用程序能感知原始主机名时,可以利用`proxy_set_header Host $host;`语句实现这一点。 - **传递真实IP地址** 为了让后端服务获取真实的客户端IP而不是Nginx所在机器的IP,应当添加如下两条命令以保留X-Forwarded-For和X-real-ip的信息: ```nginx proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; ``` - **支持WebSocket协议** 如果要使Nginx兼容Websocket连接,则需额外声明两个重要的属性——版本号(`proxy_http_version`)设为1.1和支持持久化链接(`proxy_set_connection keep-alive`) : ```nginx location /ws/ { proxy_pass http://websocket_backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } ``` - **超时时间调整** 适当延长读写操作的最大等待时限有助于提高用户体验度,特别是在网络状况不佳的情况下尤为明显: ```nginx proxy_read_timeout 60s; proxy_send_timeout 60s; ``` - **缓冲区大小控制** 通过设定合理的输入输出缓存空间大小,可有效防止因数据量过大而导致内存溢出的风险;同时也允许自定义临时文件存储位置以便于管理维护: ```nginx client_body_buffer_size 128k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; ``` 以上即是对Nginx执行代理功能过程中所涉及的关键参数进行了详细介绍。合理运用这些配置不仅能使整个系统的稳定性得到增强,还能显著改善用户的访问效率和服务质量。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值