在diff端口上运行的两个服务的nginx proxy_pass配置

时间:2019-03-04 00:01:32

标签: docker nginx docker-compose

我需要重定向或proxy_pass以下内容:

/api/v1/@server的每个请求 /@client

的所有其他内容

我有@server在端口8080上运行,@client在端口8081上运行 @client and @server作为docker容器运行。

注意。一切都应该使用https。 以下配置是我所拥有的,但是它不能正常工作

server {
  server_name example.com;

  listen 80;
  listen [::]:80 ipv6only=on;

  return 301 https://example.com$request_uri;
}

server {
    server_name example.com;

    listen 443 ssl;

    ssl_certificate     /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    ...

    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 $scheme;

    location /api/v1/ {
        try_files $uri @server;
    }

    location / {
        try_files $uri @client;
    }

    location @client {
        proxy_pass http://client:8081;
    }

    location @server {
        proxy_pass http://server:8080/api/v1/;
    }

}

1 个答案:

答案 0 :(得分:-2)

如果必须使用命名位置,则可以使用下面的error_page方法。

通过return使用未使用 HTTP状态代码和error_page设置已命名位置的代码,我们可以将请求转发到那些已命名位置:

server {
  server_name example.com;

  listen 80;
  listen [::]:80 ipv6only=on;

  return 301 https://example.com$request_uri;
}

server {
    server_name example.com;

    listen 443 ssl;

    ssl_certificate     /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    ...

    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 $scheme;

    error_page 350 = @client;
    error_page 351 = @server;

    location /api/v1/ {
        return 351;
    }

    location / {
        return 350;
    }

    location @client {
        proxy_pass http://client:8081;
    }

    location @server {
        proxy_pass http://server:8080/api/v1/;
    }

}