nginx 中的动态 proxy_pass,带有类似 gitpod 的端口

Dynamic proxy_pass in nginx with ports like gitpod

如何在 nginx 中设置动态 proxy_pass 像 gitpod.com:

我已经有通配符证书

例如,在 Gitpod 中你有一个 VM,如果你启动一个像 8081 这样的端口,你的 URL 是: https://8081-some-uuid.ws-us02.gitpod.io/

按照这个思路,我想配置类似

8082.example.com -> http://localhost:8082
8081.example.com -> http://localhost:8081
8080.example.com -> http://localhost:8080

site-enabled/example-com.config

server {
    server_name *.example.com;
    listen 80;

    location / {
        // how config this??
        proxy_pass http://localhost:(¿dynamic port?);

        proxy_set_header Connection 'upgrade';
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
    }
}

您可以使用正则表达式来捕获请求的子域部分,而不是在 server_name 中使用通配符名称。有关详细信息,请参阅 this document

例如:

server_name "~^(?<subdomain>[0-9]{4})\.example\.com$";
proxy_pass http://localhost:$subdomain;