如何配置Nginx以根据XYZ将www.myserver.com/XYZ转发到不同的服务器?

Joh*_*ang 1 nginx

假设我的机器上有多个不同的Tornado服务器.我希望根据URL调用它们.如何配置Nginx来执行此操作?例如,我在localhost:8000上有服务器A,在localhost:9000上有B. 我希望A能够处理对www.myserver.com/A和B的请求,以处理对www.myserver.com/B的请求.

Day*_*ayo 5

你尝试过像......

server {
    listen 80;
    server_name example.com;
    root /path/to/webroot;

    location / {
        # For requests to www.myserver.com/A
        location ~ ^/A {
            proxy_pass localhost:8000;
        }
        # For requests to www.myserver.com/B
        location ~ ^/B {
            proxy_pass localhost:9000;
        }
        # Some will skip the "A" or "B" flags ... so handle these
        proxy_pass localhost:9000$request_uri;
    }
Run Code Online (Sandbox Code Playgroud)

这可以扩展/细化成像......

    location / {
        # For requests to www.myserver.com/A/some/request/string
        location ~ ^/A(.+)$ {
            proxy_pass localhost:8000$1;
        }
        # For requests to www.myserver.com/B/some/request/string
        location ~ ^/B(.+)$ {
            proxy_pass localhost:9000$1;
        }
        # Some will skip the "A" or "B" flags ... so handle these
        proxy_pass localhost:9000$request_uri;
    }
Run Code Online (Sandbox Code Playgroud)

更好的方法可能是捕获一台服务器的请求,并将其余服务器默认为另一台服务器....

    location / {
        # For requests to www.myserver.com/A/some/request/string
        location ~ ^/A(.+)$ {
            proxy_pass localhost:8000$1;
        }
        # Send all other requests to alternate location.
        # Handle both well formed and not well formed ones.
        location ~ ^/(.)/(.+)$ {
            proxy_pass localhost:9000/$1;
        }
        proxy_pass localhost:9000$request_uri;
    }
}
Run Code Online (Sandbox Code Playgroud)