0

我有一个 Digital Ocean + Nginx 服务器,它托管了几个网站。现在,我想为一个网站管理多个版本。所以我需要在其网址中添加一个版本号,并希望应用以下规则:

1) 假设当前版本号是1. 任何没有版本号的 url www.myweb.com/action/...(比如action除了版本号之外的任何东西)都应该自动重写为www.myweb.com/1/action/....

2) 具有不同版本号的 URL 将被不同的服务器(即代码库 + 数据库)监听不同的端口(例如30008080)。

以下是我当前的 nginx 配置文件,有谁知道如何修改它以应用第一条规则(我们稍后可能会实施第二条规则)

server {
    listen 80;
    server_name myweb.io www.myweb.io;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;

    server_name myweb.io www.myweb.io;

    ssl_certificate /etc/letsencrypt/live/myweb.io/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/myweb.io/privkey.pem;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    ssl_ciphers 'ECDHE-RSA-......-SHA';
    ssl_session_timeout 1d;
    ssl_stapling on;
    ssl_stapling_verify on;
    add_header Strict-Transport-Security max-age=15768000;

    location = / {
        return 301 /home;
    }

    location ~ /.well-known {
        allow all;
    }

    location / {
        proxy_set_header    Host                $host;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto   $scheme;
        proxy_set_header    Accept-Encoding     "";
        proxy_set_header    Proxy               "";
        proxy_pass          https://127.0.0.1:3000;

        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection "upgrade";
    }
}
4

1 回答 1

2

因此,您需要对第一个路径不是数字的 url 进行简单的重写。所以我会在下面添加规则 1

location ~* ^/[^0-9]+/? {
  rewrite .* /1$request_uri redirect;
}

这将确保任何不以数字开头的路径都被重定向到应用程序版本的正确路径。以下是相同的测试结果

$ curl -I localhost/1/tarun
HTTP/1.1 200 OK
Server: openresty/1.11.2.2
Date: Tue, 31 Oct 2017 18:46:21 GMT
Content-Type: text/plain
Connection: keep-alive

$ curl -I localhost/tarun
HTTP/1.1 302 Moved Temporarily
Server: openresty/1.11.2.2
Date: Tue, 31 Oct 2017 18:46:27 GMT
Content-Type: text/html
Content-Length: 167
Location: http://localhost/1/tarun
Connection: keep-alive

当您想实施规则 #2时,您应该使用地图

map $request_uri $app_port {
    ~ "^/1/" "3000";
    ~ "^/2/" "3001";
    ~ "^/3/" "3002";
    default "3000";
}

server  {
  location / {
    ....
    proxy_pass http://127.0.0.1:$app_port$request_uri$is_args$args;

  }
}
于 2017-10-31T18:51:37.747 回答