首页 > 解决方案 > nginx 容器的问题与重写 url 反向代理牧场主容器

问题描述

在我的码头主机上。使用 nginx 容器,我尝试通过使用 url 名称来反向代理多个服务来识别正确的服务(portainer、rancher)。

来自https://host1/rancher => https/rancher-container 的流量

来自https://host1/porttainer => http://portainer-container:9000 的流量

我将 nginx 配置为使用 url rewrite 来转换 url,然后再将其发送到良好的服务。它适用于服务搬运工。但它不适用于 rancher 2 服务。

这是我的配置:

    location /rancher/ {
       rewrite ^/rancher^/ /$1 break;
       proxy_pass         https://rancher-container;
       proxy_redirect     off;
       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-Host $server_name;
       proxy_set_header   Upgrade $http_upgrade;
       proxy_set_header   Connection "upgrade";
       proxy_http_version 1.1;
     }

    location /portainer/ {
      rewrite ^/portainer^/ /$1 break;
      proxy_pass         http://portainer-container:9000/;
      proxy_redirect     off;
      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-Host $server_name;
      proxy_set_header   Upgrade $http_upgrade;
      proxy_set_header   Connection "upgrade";
    }

当我从我的 chromeDevTools 中查看时,我看到:

GET https://host1/rancher/ 200 OK(并像这样返回索引页面): <!DOCTYPE html> <html> ... <link id="vendor" rel="stylesheet" href="/assets/vendor.css"> ... <script src="/assets/vendor-ebb1f9e6b4381d69a55448a2a5d7e4c9.js"></script> <script src="/assets/ui-72ee502ee50a84d0f416c3164137307d.js"></script> ... GET https://host1/assets/vendor.css net::ERR_ABORTED 404 GET https://host1/assets/vendor-ebb1f9e6b4381d69a55448a2a5d7e4c9。 js net::ERR_ABORTED 404 GET https://host1/assets/ui-72ee502ee50a84d0f416c3164137307d.js

我认为我的网络浏览器尝试在 html 页面上定义资源(css、js、img ..etc),其相对 URL 为“/assets/”到“ https://host1/assets ”。或者好的 url 是' https://host1/racher/assets '。

有什么解决办法吗?

标签: dockernginxreverse-proxyrancher

解决方案


检查网站。可能在 HTML 代码中,您的网站不知道它不是在额外路径上运行,而是假定它在 root 上。也许有一些开关可以让您为网站设置一个基本路径以知道它在哪里。

不幸的是,这是一个相当普遍的问题。默认代理标头不发送原始路径,因此隐藏在后面的服务通常不知道请求是针对 / 以外的其他内容的。

如果代理背后的服务是您的,您可以传递一些额外的标头,例如 x-proxy-urlpath 并通知服务它应该呈现包含该路径的链接。

如果没有,并且您无法在网站中设置基本 url - 最好的解决方案是使用子域和基于主机的代理。


推荐阅读