我有一台Digital Ocean + Nginx服务器,它托管多个网站。现在,我想为一个网站管理多个版本。所以我需要在其网址中添加版本号,并希望应用以下规则:
1)假设当前版本号为1
。任何没有www.myweb.com/action/...
版本号的网址(其中action
可以是除版本号之外的任何内容)都应自动重写为www.myweb.com/1/action/...
。
2)具有不同版本号的网址将由不同的服务器(即代码库+数据库)处理,监听不同的端口(例如3000
和8080
)。
以下是我目前的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";
}
}
答案 0 :(得分: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;
}
}