Bootstrap

nginx 实现接口版本控制

背景

近期项目做了不兼容的升级,项目上线时需要考虑两个版本的兼容。由于项目代码并未考虑接口版本控制,因此需要部署一套新版本的系统,并使用 nginx 对两个版本的接口进行分发。

实现思路

考虑了两种实现实现方式:

考虑项目情况,最终决定使用第二种方式,因为如果使用第一种方式会存在如下问题:

实现

项目服务使用 php 实现,并使用了 laravel 框架,如果是其他技术实现,需要做相应的修改。

实现步骤:

server {
    listen 80;
    listen       443 ssl;
    
    server_name  api.xxx.com;

    index  index.html index.htm index.php;

    # 新版本配置
    location /v2/ {
        root   /var/www/code-v2/public;
        
        # 注意这里重定向到 php 代码时添加了 /v2 前缀
        try_files $uri $uri/ /v2/index.php?$query_string;
    }

    # 这里捕获去除 /v2 前缀的部分,捕获内容会放到 $1 变量中
    location ~ /v2(/.*\.php) {
        root   /var/www/code-v2/public;

        fastcgi_pass localhost:9001;

        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        
        # 这里使用 $1 作为脚本名(fastcgi_script_name)
        fastcgi_param SCRIPT_FILENAME $document_root$1;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }


    # 旧版本配置
    location / {
        root   /var/www/code/public;
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        root   /var/www/code/public;

        fastcgi_pass localhost:9000;

        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

注意事项