详解Ubuntu/CentOS下Apache多站点配置

2019-01-17 00:02:30王旭

针对 wordpress 做同样的操作。

第四步:修改 /etc/hosts 文件

打开查看 /etc/hosts 文件,开头是:

127.0.0.1 localhost

我们在该行后面添加:

# modified by zhongjin on 2016-12-21 冬至 127.0.0.1 www.jb51.net 127.0.0.1 www.wordpress.com #保存退出

第五步:重启 apache 服务器并测试

重启 apache 服务器使得配置生效:

systemctl restart apache2.service

在浏览器(如果是桌面版的话)中访问www.jb51.net或 www.wordpress.com,看看是否输出了 index.php 文件中的内容。

如果你不是桌面版(服务器),那么可以使用命令行测试:

curl www.jb51.net

看看返回的字符串是不是正确输出!

Centos 环境下:

我的环境是:操作系统:Centos 7

apache 服务: Apache/2.4.6 (CentOS)(通过 httpd -v 获取)

在这里我们实现 Ubuntu 环境下同样的效果。

Centos 下,apache 的服务叫 httpd,主配置文件为 /etc/httpd/conf/httpd.conf,我们浏览 httpd.conf 文件,搜索关键字 vhost,发现根本找不到相关的东西,不过在最后两行有以下内容:

# Load config files in the "/etc/httpd/conf.d" directory, if any. IncludeOptional conf.d/*.conf

难道虚拟主机的配置也在 /etc/httpd/conf.d 下面?LZ 去看了一下该目录下面所有文件的内容,发现根本没有关于虚拟主机的配置,如果你再仔细观察 http.conf 配置文件,你就会发现,其实在 Centos 下,其默认主机只有 localhost ==> /var/www/html ,如果需要的话,我们得自己扩展了。

我们有两种方式实现自己的扩展,一种是直接在 /etc/httpd/conf/httpd.conf 后面追加配置内容,一种是在外部文件先配置好,再类似 IncludeOptional conf.d/*.conf 那样引入我们的配置。一般不推荐直接修改主配置文件,所以我们使用第二种方式。

我们还是模仿上面的配置:

第一步:新增站点配置文件

cd /etc/httpd sudo mkdir vhost-conf.d

我们在 vhost-conf.d 目录下新增我们的虚拟主机配置文件 www-jb51-net.conf 和 www-wordpress-com.conf,以 www-jb51-net.conf 为例,我们输入以下内容:

<VirtualHost *:80> #Created by zhongjin on 2016-12-21 冬至 Serveradmin jb51@jb51.com ServerName www.jb51.net DocumentRoot /home/www/jb51 <Directory "/home/www/jb51"> Options FollowSymLinks AllowOverride All #Require all denied Require all granted </Directory> </VirtualHost>

针对 www-wordpress-com.conf 改变相应的配置,即修改 ServerName 为 www.wordpress.com,DocumentRoot 和 Directory 修改为 /home/www/wordpress。