简体   繁体   English

Nginx 如何按位置路由到反向代理

[英]Nginx How do i route to reverse proxy by location

Currently i'm using nginx server and using nodejs server as reverse proxy.目前我正在使用 nginx 服务器并使用 nodejs 服务器作为反向代理。 I want to make the nginx server proxy_pass different server by location.我想让 nginx 服务器 proxy_pass 按位置不同的服务器。

So, lets say my domain is subdomain.domain.com .所以,假设我的域是subdomain.domain.com

When loading subdomain.domain.com/ , this should serve static files.加载subdomain.domain.com/时,这应该提供 static 文件。

When loading subdomain.domain.com/example1/req1/req2 , this should route to 127.0.0.1:3000/req1/req2 .加载subdomain.domain.com/example1/req1/req2时,应该路由到127.0.0.1:3000/req1/req2

When loading subdomain.domain.com/example2/req1/req2 , this should route to 127.0.0.1:8080/req1/req2 .加载subdomain.domain.com/example2/req1/req2时,应该路由到127.0.0.1:8080/req1/req2

But my configuration routes subdomain.domain.com/example1/req1/req2 to 127.0.0.1:3000/example1/req1/req2 resulting error.但是我的配置将subdomain.domain.com/example1/req1/req2路由到127.0.0.1:3000/example1/req1/req2导致错误。 (nodejs returns Cannot GET /example1) (nodejs返回Cannot GET /example1)

How should I write this nginx conf file properly?我应该如何正确编写这个 nginx conf 文件?

Try use rewrite directive in location block.尝试在位置块中使用重写指令。

Something like:就像是:

location /example1/ {
  rewrite     ^/example1/(.*)$ /$1 break;
  proxy_pass  http://xxxxxx;
}

You can check documents related to rewrite module at http://nginx.org/en/docs/http/ngx_http_rewrite_module.html您可以在http://nginx.org/en/docs/http/ngx_http_rewrite_module.html查看与重写模块相关的文档

You need to add below code snippet to your nginx.conf.您需要将以下代码片段添加到您的 nginx.conf 中。

    server subdomain.domain.com;
        location / {
            rewrite     ^/example1/(.*)$ /$1 break;
            proxy_pass http://127.0.0.1:3000;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM