如何创建基于名称的Apache虚拟主机

时间:2019-11-20 08:54:17  来源:igfitidea点击:

虚拟主机是指在一台Apache服务器上维护多个网站的做法。

如果要配置基于名称的虚拟主机,NameVirtualHost指令是必需的指令。

使用NameVirtualHost指令,可以指定服务器将接收基于名称的虚拟主机的请求的IP地址。这通常是基于名称的虚拟主机名解析到的地址。

Apache 2中基于名称的虚拟主机配置

例如,假设IP地址是203.54.2.5。

编辑httpd.conf文件:

# vi /etc/httpd/conf/httpd.conf

设置NameVirtualHost:

NameVirtualHost 203.54.2.5:80

假设有两个虚拟机,对应域名分别
theitroad.org 和 theitroad.tech

theitroad.org 虚拟机的配置

<VirtualHost theitroad.org/>
 ServerAdmin [email protected]
 DocumentRoot /var/www/theitroad.org
 ServerName theitroad.org
 ServerAlias www.theitroad.org
 ErrorLog /var/logs/httpd/theitroad.org/error_log
 CustomLog /var/logs/httpd/theitroad.org/access_log common
 </VirtualHost>

theitroad.tech 虚拟机的配置

<VirtualHost theitroad.tech/>
 ServerAdmin [email protected]
 DocumentRoot /var/www/theitroad.tech
 ServerName theitroad.tech
 ServerAlias www.theitroad.tech
 ErrorLog /var/logs/httpd/theitroad.tech/error_log
 CustomLog /var/logs/httpd/theitroad.tech/access_log common
 </VirtualHost>

重新启动Apache:

# /etc/init.d/httpd restart

需要在域名控制面板中(买域名的地方)
设置A地址,指向203.54.2.5 。
还要确保创建/var/logs/httpd/domain-name目录,并将ftp用户目录指向相应的/var/www/domain-name目录。

虚拟主机和IP地址

如果要在计算机上维护多个域/主机名,则可以为其设置VirtualHost容器。

大多数配置仅使用基于名称的虚拟主机,因此可以在配置文件中直接使用星号,如下所示:

NameVirtualHost *:80
 
<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "/usr/local/docs/theitroad.tech"
    ServerName theitroad.tech
    ServerAlias www.theitroad.tech
    ErrorLog "/var/log/theitroad.tech-error_log"
    CustomLog "/var/log/theitroad.tech-access_log" common
</VirtualHost>
 
<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "/var/www/html/theitroad.org/"
    ServerName theitroad.org
    ErrorLog "/var/log/theitroad.org-error_log"
    CustomLog "/var/log/theitroad.org-access_log" common
</VirtualHost>