需求说明
app端请求头添加自定义字段:"version: 3",nginx判断是否有"version: 3"这样的请求头,若有这样的请求头,则将请求转发到新发布的后端服务器,若没有这样的请求头,则将请求转发到旧的后端服务器。
nginx配置实现
- http模块内新增配置:
map $http_version $version{
default 0;
"*version:*3*" 3;
}
##自定义模块$http_version
##$version新的名称
##default 0:表示$version的默认值未0
##"version:*3*":匹配到version: 3时$version的值为3,*是通配符,所有字符任意次
- server模块新增配置
underscores_in_headers on;
#nginx启用接受自定义头部
- location模块配置判断头部和分流
location ~ [^/]\.php(/|$){
try_files $uri =404;
# 注意下面空格不可缺少,否则nginx -t会有语法错误
if ($http_version = 3) {
#如果version = 3 则将请求转发到https://____.com
proxy_pass https://____.com;
break;
}
#默认,未在请求头获取到version = 3 的请求将转发至本地的后端服务器
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
根据location分流到不同的后端服务
- 新版本app的所有请求地址加/v1.2的前缀;
- nginx部分(server 模块内的部分)配置
location /v1.2 {
rewrite /v1.2/(.*) /$1 break;
proxy_pass https://test2.api.dajxyl.com;
}
location ~ ^(.+\.php)(.*)$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
fastcgi_param PHP_ADMIN_VALUE "open_basedir=/home/www/:/tmp/:/proc/";
root /home/www/dajx-api/web;
index index.html index.php;
access_log /home/wwwlogs/dajx-api.access.log;
error_log /home/wwwlogs/dajx-api.error.log;
location / {
try_files $uri $uri/ /index.php?$args;
}