上面两篇文章介绍了如何安装CentOS系统和配置PHP开发环境,这次介绍如何配置Apache虚拟主机。
参考了CentOS7 初次安装记录(五)配置 apache 虚拟主机,修改了部分内容。
配置Apache虚拟主机
1)修改vhost.conf文件,设置虚拟域名;
配置虚拟主机我知道的有两种方式,一是直接在主配置文件(/etc/httpd/conf/httpd.conf)修改,但是该文件比较重要,要是改错了地方就会很麻烦;二是在 /etc/httpd/conf.d/ 下面建立一个 vhost.conf 文件,这样比较容易管理。这里采用第二种。
//新建一个名为vhost.conf的文件
vim /etc/httpd/conf.d/vhost.conf
//下面是我的vhost.conf里的内容
<VirtualHost *:80>
#绑定的主域
ServerName localhost
#网站主目录
DocumentRoot /var/www/
<Directory "/var/www">
Options FollowSymLinks ExecCGI
AllowOverride All
Order allow,deny
Allow from all
Require all granted
</Directory>
</VirtualHost>
#
# 测试网站一
#
<VirtualHost *:80>
#绑定的主域
ServerName test.com
#绑定的子域名
ServerAlias www.test.com
#网站主目录
DocumentRoot /home/visionz/website/test/
DirectoryIndex index.html index.php
#日志配置
ErrorLog /home/visionz/web_log/test.error.log
CustomLog /home/visionz/web_log/test.access.log common
#ServerSignature Off
</VirtualHost>
#测试一的配置
<Directory "/home/visionz/website/test/">
Options FollowSymLinks ExecCGI
AllowOverride All
Order Deny,Allow
Allow from All
Require all granted
</Directory>
// 如果有更多内容,重复上面的
2)修改hosts文件,指定域名对应地址;
因为当前DNS服务器是无法将我们的配置的虚拟域名解析成我们的IP地址,因此需要配置hosts,把test.com指向当前主机IP。
//编辑hosts文件
vim /etc/hosts
//以下是我hosts文件内容
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
127.0.0.1 test.com www.test.com
3)新建文件夹website、web_log、以及index.php文件;
在步骤一,我们的项目位置设置在/home/visionz/下面,因此需要建立相应的文件夹和文件
//建立website、web_log文件夹
mkdir /home/visionz/website
mkdir /home/visionz/web_log
//建立index.php文件
mkdir /home/visionz/website/test
touch /home/visionz/website/test/index.php
//修改index.php文件
vim /home/visionz/website/test/index.php
//内容为
<?php
echo "hello world.";
?>
//重启服务
systemctl restart httpd.service
4)把visionz文件夹权限设置成777;
在步骤三重启服务后,进行访问test.com,发现出现“You don’t have permission to access / on this server”的报错。
查看错误日志文件,发现以下信息:
[core:crit] [pid 5129] (13)Permission denied: [client 127.0.0.1:37927] AH00529: /home/visionz/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable and that '/home/visionz/' is executable
因为web的数据目录为/home/visionz/website目录。因visionz目录的权限为700,导致了其他用户无法读取文件。
将visionz目录的权限修改为777,问题解决。
//修改权限
chmod 777 /home/visionz
//重启服务
systemctl restart httpd.service
5)在本机访问虚拟机虚拟域名;
如果有在本机访问虚拟机的必要,也是通过修改hosts文件,把虚拟域名指向虚拟主机IP。
我的电脑是windows系统,因此修改C:\windows\system32\drivers\etc下面的hosts文件即可。
//在尾部增加下面语句即可
192.168.2.110 www.test.com test.com
到这里,应该可以在你的浏览器访问www.test.com可以看到下面内容