Nginx 选择随机位置块

Nginx 选择随机位置块

我想根据路径将请求重定向到不同的服务器,因此我在 Nginx 配置中使用以下 http 块:

http {
  include  /etc/nginx/mime.types;
  default_type  application/octet-stream;
  index index.html index.htm;

  server {
    access_log  /var/log/nginx/staging.access.log main buffer=32k;
    error_log   /var/log/nginx/staging.error.log error;
    listen      80;
    root        /dev/null;

    location / {
      proxy_pass        http://core:80;  # returns "Core Service"
    }

    location /page/ {
      rewrite ^/page(/.*)$ $1 break;
      proxy_pass        http://page:80;  # returns "Page Service"
    }

    location /auth/ {
      rewrite ^/auth(/.*)$ $1 break;
      proxy_pass        http://auth:80;  # returns "Auth Service"
    }
  }
}

据我了解,Nginx 文档中,Nginx 应该使用最匹配的位置块,因此我期望它curl http://hostname/应该返回“核心服务”、curl http://hostname/auth“身份验证服务”和curl http://hostname/“页面服务”。然而,Nginx 使用随机位置块:

$ curl  http://hostname/
Core Service
$ curl  http://hostname/
Auth Service
$ curl  http://hostname/
Page Service
$ curl  -L http://hostname/page
Auth Service
$ curl  -L http://hostname/page
Auth Service
$ curl  -L http://hostname/page
Core Service

我的配置有什么问题?

答案1

您在每个匹配项的末尾添加了尾随 / 字符,请尝试进行如下编辑:

location /page {
  rewrite ^/page(/.*)$ $1 break;
  proxy_pass        http://page:80;  # returns "Page Service"
}

location /auth {
  rewrite ^/auth(/.*)$ $1 break;
  proxy_pass        http://auth:80;  # returns "Auth Service"
}

答案2

顺便说一句,你应该简化你的配置:

server {
    access_log  /var/log/nginx/staging.access.log main buffer=32k;
    error_log   /var/log/nginx/staging.error.log error;
    listen      80;

    location / {
      proxy_pass        http://core:80/;  # returns "Core Service"
    }

    location /page/ {
      proxy_pass        http://page:80/;  # returns "Page Service"
    }

    location /auth/ {
      proxy_pass        http://auth:80/;  # returns "Auth Service"
    }
}

相关内容