将请求转发给 KVM 主机上的几位客户机之一?

将请求转发给 KVM 主机上的几位客户机之一?

我有一台 Ubuntu 主机和 3 个客户机。它们都在端口 80 上运行不同的 Web 服务。我如何告诉主机根据主机名将请求转发给适当的客户机?

主机:example.com

访客:git.example.com、www.example.com、psql.example.com

答案1

由于您需要根据主机名而不是端口进行路由,因此将流量 NAT 到虚拟机的 iptables 解决方案已经失效。

您剩下要做的就是以反向代理模式运行 Web 服务器,该服务器读取请求主机标头并根据请求的标头代理到不同的私有 IP。

确切的配置将取决于您使用的 Web 服务器,而您选择哪个 Web 服务器将取决于您需要哪些功能(SSL?)以及个人偏好。请告诉我您更喜欢哪个 Web 服务器,如果需要,我可以编辑答案以包含示例配置。

编辑:基本 nginx 配置:

http {

    # ...existing config basics... server_name, NOT servername

    server {
        listen 80;
        server_name git.example.com;
        location / {
            # git server IP below:
            proxy_pass http://10.x.x.x:80/;
            # re-send the host header - this may not be necessary
            proxy_set_header Host $host;
            # set the X-Forwarded-For header, so that the public IP of the client is available to the backend server
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
    server {
        listen 80;
        server_name psql.example.com;
        location / {
            # psql server IP below:
            proxy_pass http://10.x.x.x:80/;
            # re-send the host header - this may not be necessary
            proxy_set_header Host $host;
            # set the X-Forwarded-For header, so that the public IP of the client is available to the backend server
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
    server {
        listen 80;
        server_name www.example.com;
        location / {
            # www server IP below:
            proxy_pass http://10.x.x.x:80/;
            # re-send the host header - this may not be necessary
            proxy_set_header Host $host;
            # set the X-Forwarded-For header, so that the public IP of the client is available to the backend server
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

答案2

您必须在可以访问互联网的主机上安装 Web 服务器并使用“基于名称的虚拟主机配置”(尝试在 Google 中使用您的 Web 服务器的名称)。每个基于名称的虚拟服务器都必须是一个虚拟服务器的代理。您可以随时使用 apache、nginx、lighttpd...

答案3

桥接所有连接。这样,您的客户机就可以在与主机相同的网络上获取 IP。现在在 DNS 中为这三个客户机添加“A”记录。

请记住,如果请求是针对 git.example.com 的,除非您为其设置了“CNAME”,否则它永远不会到达 example.com。

[根据评论进行编辑]
由于您无法使用 DNS,我建议根本不要运行虚拟机。而是创建一些虚拟主机并使用它们。在您的 nginx 中只需定义多个 server_name。检查nginx 维基百科举个例子。

相关内容