系统相关
首页 > 系统相关> > linux – 为什么所有不匹配的流量都转到第一个VirtualHost而不是httpd.conf中的默认站点配置

linux – 为什么所有不匹配的流量都转到第一个VirtualHost而不是httpd.conf中的默认站点配置

作者:互联网

我一直想知道为什么所有不匹配的流量都转到第一个VirtualHost而不是httpd.conf中的默认站点配置?

假设httpd.conf尚未编辑.

我创建了一个名为/etc/httpd/conf.d/vhost.conf的文件

具有以下内容:

<VirtualHost *:80>
        ServerName website.com
        ServerAlias www.website.com
        DocumentRoot "/site1"
        <Directory "/site1">
                AllowOverride All
                Require all granted
        </Directory>

        Some Rules Here
</VirtualHost>
<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com
        DocumentRoot "/site2"
        <Directory "/site2">
                AllowOverride All
                Require all granted
        </Directory>

        Some Rules Here
</VirtualHost>

以上示例,如果您发送stackoverflow.com请求,您将被过滤到第一个vhost,无论过滤器是什么,而不是httpd.conf中的默认网站

我错过了什么?

解决方法:

你没有做错什么;这就是Apache Name-based Virtual Hosts的工作方式:

在Apache上配置虚拟主机后,即原始默认Web服务器
(如果有的话)成为另一个虚拟主机;这个没什么特别的
在httpd.conf中配置的Web服务器.默认虚拟主机(对于Apache“侦听”的IP地址)只是Apache配置文件中列出的第一个:

If you are adding virtual hosts to an existing web server, you must also create a <VirtualHost> block for the existing host. The ServerName and DocumentRoot included in this virtual host should be the same as the global ServerName and DocumentRoot. List this virtual host first in the configuration file so that it will act as the default host.

另外,从同一页面:

If no matching virtual host is found, then the first listed virtual host that matches the IP address will be used.

As a consequence, the first listed virtual host is the default virtual host. The DocumentRoot from the main server will never be used when an IP address matches the NameVirtualHost directive. If you would like to have a special configuration for requests that do not match any particular virtual host, simply put that configuration in a <VirtualHost> container and list it first in the configuration file.

我发现虚拟主机如何在Apache上工作的最佳总体描述是An In-Depth Discussion of Virtual Host Matching.这也指定了,

The first name-based vhost in the configuration file for a given IP:port pair is significant because it is used for all requests received on that address and port for which no other vhost for that IP:port pair has a matching ServerName or ServerAlias. It is also used for all SSL connections if the server does not support Server Name Indication.

The first vhost in the config file with the specified IP address has the highest priority and catches any request to an unknown server name, or a request without a Host: header field (such as a HTTP/1.0 request).

标签:apache,linux,virtualhost,centos,httpd-conf
来源: https://codeday.me/bug/20190628/1315481.html