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

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

<VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>

DocumentRoot 是这个站点的根目录,这样 Apache2 启动时会扫描 /etc/apache2/sites-enabled 中可用的 website 配置并加载。当用户访问localhost:80 时,Apache2 就将 default 站点根目录 /var/www/html 下的index.html(或 index.PHP 等,可配置)作为请求的回应返回给浏览器,你就会欣赏到的就是 /var/www/html/index.html 这个文件中的内容了。

Apache2的默认站点我们不要去动它。我们新增站点配置来满足我们的要求。

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

在 /etc/apache2/sites-available 目录中中建立两个站点的配置文件 www-jb51-net.conf 和 www-wordpress-com.conf:

#进入虚拟主机配置文件夹 cd /etc/apache2/sites-available/ #复制默认的虚拟主机配置文件 sudo cp 000-default.conf www-jb51-net.conf sudo cp 000-default.conf www-wordpress-com.conf

编辑这两个配置文件,以 www-jb51-net.conf为例:

# Created By zhongjin on 2016-12-12 冬至 <VirtualHost *:80> ServerAdmin 1054840542@qq.com ServerName www.jb51.net DocumentRoot /home/www/jb51 <Directory "/home/www/jb51"> Options FollowSymLinks AllowOverride All #Require all denied Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>

注意上面配置中:ServerName、DocumentRoot 和 Directory 是我们重点关注的配置点。jb51的 ServerName 为www.jb51.net,根目录为 /home/www/jb51,Directory 同 DocumentRoot。

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

第二步:在sites-enabled目录下建立符号链接

cd /etc/apache2/sites-enabled #建立对应的软链接 sudo ln -s /etc/apache2/sites-available/www-jb51-net.conf /etc/apache2/sites-enabled/www-jb51-net.conf sudo ln -s /etc/apache2/sites-available/www-wordpress-com.conf /etc/apache2/sites-enabled/www-wordpress-com.conf

第三步:在对应目录放入项目代码

如上面所示,我们的 jb51项目代码放在 /home/www/jb51 ,wordpress 项目代码放在 /home/www/wordpress,那么我们在对应目录下创建对应目录并赋予相应权限,以 jb51为例:

sudo mkdir -p /home/www/linuxidc

然后在 /home/www/jb51 下放入项目代码,这里为了测试就新建 index.php,内容如下:

<?php echo "hello,welcome to jb51!";

赋予相应的权限:

sudo chmod -R 777 /home/www/jb51