针对特定路径的nginx代理请求

针对特定路径的nginx代理请求,nginx,Nginx,是否可以将特定路径的请求传递到不同的上游服务器 以下是我的nginx站点配置: upstream example.org { server 127.0.0.1:8070; keepalive 8; } server { listen 0.0.0.0:80; server_name example.org www.example.org; access_log /var/log/nginx/example.org.log; location /

是否可以将特定路径的请求传递到不同的上游服务器

以下是我的nginx站点配置:

upstream example.org {
    server 127.0.0.1:8070;
    keepalive 8;
}

server {
    listen 0.0.0.0:80;
    server_name example.org www.example.org;
    access_log /var/log/nginx/example.org.log;

    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://example.org;
      proxy_redirect off;
    }
 }
目前,对该站点的请求被重定向到端口8070上运行的Node.js实例

我希望将对该站点的路径以/services开头的请求重定向到端口8080上运行的另一个Node.js实例


这可能吗?当然,这是怎么回事?

是的,只需添加另一个位置块:

upstream example.org {
    server 127.0.0.1:8070;
    keepalive 8;
}
upstream other.example.org {
    server 127.0.0.1:8080;
    keepalive 8;
}

server {
    listen 0.0.0.0:80;
    server_name example.org www.example.org;
    access_log /var/log/nginx/example.org.log;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_redirect off;

    location / {
      proxy_pass http://example.org;
    }

    location /services {
      proxy_pass http://other.example.org;
    }
 }

注意:我将所有共享代理指令提取到服务器块中,以便它们不会在每个位置块中重复。如果它们在不同的位置之间不同,您必须将它们再次移动到位置块中…

此操作有效,但现在对“”的请求会被添加到它的末尾吗?例如,我想转发到,但现在是转发到@eat sleep code。您可以通过更改proxy_-pass指令以包含尾部斜杠来解决此问题,例如
proxy_-passhttp://other.example.org/;。有关更多信息,请参阅文档: