如何在CentOS7上配置Apache虚拟主机?

前面我们介绍了,相信你已经可以在CentOS7上部署自己的lamp环境了,本文继续介绍Apache虚拟主机的配置,也就是站点配置和管理。

为了便于日后网站文件数据的管理我们要先做好计划:站点文件存放在什么地方?通常情况下如果你使用的是云主机,我们建议你放在挂载数据磁盘的目录中,比如你挂载目录是/mnt/那么我建议你的网站数据应该是这样子的:

/mnt/www/siteA.com/public_html/
/mnt/www/siteB.com/public_html/
/mnt/www/siteC.com/public_html/
...

也就是说先准备好一个目录/mnt/www/存放网站,/public_html/用来上传网站主目录,public_html同级目录会放网站log文件、.htpasswd密码文件什么的。

下面切入正题,开始配置Apache虚拟主机

建立站点目录

mkdir -p /mnt/www/example.com/public_html
mkdir -p /mnt/www/example2.com/public_html

在各自目录下建立一个文件

vi /mnt/www/example.com/public_html/index.html
<html>
  <head>
    <title>Welcome to Example.com!</title>
  </head>
  <body>
    <h1>Success! The example.com virtual host is working!</h1>
  </body>
</html>
vi /mnt/www/example.com2/public_html/index.html
<html>
  <head>
    <title>Welcome to Example2.com!</title>
  </head>
  <body>
    <h1>Success! The example2.com virtual host is working!</h1>
  </body>
</html>

配置Apache

mkdir /etc/httpd/sites-available
mkdir /etc/httpd/sites-enabled

这两个文件夹分别用来存放网站配置文件

接下来配置httpd.conf文件

vi /etc/httpd/conf/httpd.conf

使用shift+g,让光标移动至末尾,按i添加一行

IncludeOptional sites-enabled/*.conf

:wq 保存退出

建立网站配置文件

vi /etc/httpd/sites-available/example.com.conf

在文件中录入:

<VirtualHost *:80>
    ServerName www.example.com    
    ServerAlias example.com    
    DocumentRoot /mnt/www/example.com/public_html    
    ErrorLog /mnt/www/example.com/error.log    
    CustomLog /mnt/www/example.com/requests.log combined    
    <Directory /mnt/www/example.com/public_html>    
        Options FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

参数说明:

  • ServerName #服务名
  • ServerAlias #绑定域名,多个域名用空格隔开,注意:如果你用ProcessWire做网站群要在这里绑定你的所有域名
  • DocumentRoot #站点根目录
  • ErrorLog #网站访问错误日志存放目录
  • CustomLog #网站访问日志
  • Directory #站点根目录
  • Options #Options指令的完整语法为:Options [+|-]option [[+|-]option] ...。简而言之,Options指令后可以附加指定多种服务器特性,特性选项之间以空格分隔。更多Options介绍点击这里。注意这里如果添加上Indexes的时候是会将没有索引文件(index.html/index.php...)文件列出在当前目录,如果无特殊需要切勿使用此功能。

你可以根据配置修改,这时候我们可以直接复制一份站点exmple2.com:

cp /etc/httpd/sites-available/example.com.conf /etc/httpd/sites-available/example2.com.conf

编辑example2.com.conf

vi /etc/httpd/sites-available/example2.com.conf

可以使用命令批量替换

:%s#example.com#example2.com#g

建立软连接:

ln -s /etc/httpd/sites-available/example.com.conf /etc/httpd/sites-enabled/example.com.conf
ln -s /etc/httpd/sites-available/example2.com.conf /etc/httpd/sites-enabled/example2.com.conf

测试配置文件语法是否正确:

apachectl configtest

如果提示Syntax OK测表示配置无误,否则请根据提示检查conf配置文件

最后我们重启一下httpd

systemctl restart httpd

Post Comment