当前位置 主页 > 服务器问题 > Linux/apache问题 > 最大化 缩小

    单台服务器中利用Apache的VirtualHost如何搭建多个Web站点详解

    栏目:Linux/apache问题 时间:2019-10-09 22:07

    前言

    本文将详细记录一下如何在单台服务器上,利用apache的virtualhost(虚拟主机)来搭建多个不同的web站点,并且每个站点独立管理自己的session,下面话不多说了,来一起看看详细的介绍吧。

    开发环境

    先说下我各项开发环境参数:

    操作系统: RedHat6.7(CentOS) WEB服务器:apache2.2 php5.6.30

    修改Apache配置

    apache2.2 的配置文件路径在 /etc/httpd/conf/httpd.conf

    我们用下面的命令修改apache的配置文件:

    $ vim /etc/httpd/conf/httpd.conf

    添加监听端口

    找到如下的部分,

    #
    # Listen: Allows you to bind Apache to specific IP addresses and/or
    # ports, in addition to the default. See also the <VirtualHost>
    # directive.
    #
    # Change this to Listen on specific IP addresses as shown below to
    # prevent Apache from glomming onto all bound IP addresses (0.0.0.0)
    #
    #Listen 12.34.56.78:80
    Listen 80

    默认的话,应该只会监听80端口,这里我们在后面加上用于另外站点的端口号。例如我们A站点是默认的80端口,B站点计划搭建在8080端口上,最终的配置文件修改成

    ...
    #Listen 12.34.56.78:80
    Listen 80
    Listen 8080

    启动并添加VirtualHost

    接着在配置文件中找到下面的章节:

    ### Section 3: Virtual Hosts
    #
    # VirtualHost: If you want to maintain multiple domains/hostnames on your
    # machine you can setup VirtualHost containers for them. Most configurations
    # use only name-based virtual hosts so the server doesn't need to worry about
    # IP addresses. This is indicated by the asterisks in the directives below.
    #
    # Please see the documentation at
    # <URL:http://httpd.apache.org/docs/2.2/vhosts/>
    # for further details before you try to setup virtual hosts.
    #
    # You may use the command line option '-S' to verify your virtual host
    # configuration.
    
    #
    # Use name-based virtual hosting.
    #
     NameVirtualHost *:80
     NameVirtualHost *:8080

    上面的代码是我已经修改好的,默认的话,最后两行NameVirtualHost应该也是被注释掉了。 因为我们要启用虚拟主机,所以这里就把我们之前监听的两个端口都设置好。

    同时,将之后的配置文件修改成如下的样子,我们先来设置默认的80端口的站点A

    #
    # VirtualHost example:
    # Almost any Apache directive may go into a VirtualHost container.
    # The first VirtualHost section is used for requests without a known
    # server name.
    #
    <VirtualHost *:80>
    # ServerAdmin webmaster@dummy-host.example.com
     DocumentRoot /var/www/webA
     ServerName webA
    # ErrorLog logs/dummy-host.example.com-error_log
    # CustomLog logs/dummy-host.example.com-access_log common
    </VirtualHost>

    默认的Apache是没有开启VirtualHost的,所以这些代码都是被注释掉了的,我们这里只需要把DocumentRoot和ServerName所在的行去掉注释并且编辑下就好了。

    DocumentRoot指的的是我们A站点的网站根目录位置

    接下来再补充上8080端口的B站点信息就好了。

    <VirtualHost *:8080>
     DocumentRoot /var/www/webB
     ServerName webB
    </VirtualHost>