我第一次尝试设置nginx。 我有以下问题我想解决。
我有两个版本的后端v1和v2。
用户被路由到“/ v2”(proxy_pass'127.0.0.1:3000;')
Traffic tru“/”(javascript +套接字)已路由到同一服务器'127.0.0.1:3000;'通过查看cookie。
继承我的问题,cookie不存在,因此将返回404
有什么建议吗?
map $cookie_version $site_version {
default "";
"v1" "version=v1;Domain=localhost;Path=/";
"v2" "version=v2;Domain=localhost;Path=/";
}
server {
listen 8081;
server_name localhost;
location / {
if ($cookie_version ~* "v1") {
proxy_pass http://127.0.0.1:8080;
}
if ($cookie_version ~* "v2") {
proxy_pass http://127.0.0.1:3000;
}
}
location /v1 {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_http_version 1.1;
set $cookie_version "v1";
add_header Set-Cookie $site_version;
rewrite ^/v1(.*) /$1 break;
proxy_pass http://127.0.0.1:8080;
}
location /v2 {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_http_version 1.1;
set $cookie_version "v2";
add_header Set-Cookie $site_version;
rewrite ^/v2(.*) /$1 break;
proxy_pass http://127.0.0.1:3000;
}
}
答案 0 :(得分:0)
首先,阅读为什么如果是邪恶http://wiki.nginx.org/IfIsEvil。请改用map
。
我的建议是:
map $cookie_version $mybackend {
default "127.0.0.1:3000";
"v1" "127.0.0.1:8080";
"v2" "127.0.0.1:3000";
}
...
location / {
proxy_pass http://$mybackend;
}
...
location ~ ^/(?<cver>v[12])/ {
...
add_header Set-Cookie "version=$cver;Domain=localhost;Path=/";
rewrite ^/v[12]/(.*)$ /$1 redirect;
}