nginx 配置:如何根据URL参数转发到不同的端口?

nginx 配置:如何根据URL参数转发到不同的端口?

我是 nginx 新手。以下是我想要的:

http://example.com/3000/lorem/ipsum -> http://example.com:3000/lorem/ipsum
http://example.com/3001/lorem/ipsum -> http://example.com:3001/lorem/ipsum
http://example.com/3002/lorem/ipsum -> http://example.com:3002/lorem/ipsum

我已经做了一些事情,所以它有效,但我认为有更好的方法:

location /3000/ {
    proxy_pass http://localhost:3000/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

location /3001/ {
    proxy_pass http://localhost:3001/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

location /3002/ {
    proxy_pass http://localhost:3002/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

我已阅读了许多使用正则表达式解决此问题的帖子,但我无法弄清楚具体用法。

答案1

下面修复了该问题:

location ~ ^/300(0|1|2) {
    rewrite ^/300(0|1|2)(/?)(.*) /$3 break;
    proxy_pass http://localhost:300$1;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

答案2

这应该可以解决问题:

location ~ /(300[0-2])(/|)(\S+|)$ {
    proxy_pass http://127.0.0.1:$1/$3;
}

请注意,如果端口号不在 URI 的最左侧,则可能会导致问题,例如:example.com/lorem/ipsum/3000.html将代理至本地主机:3000/lorem/ipsum/.html这当然是废话。

相关内容