CentOS Apache如何设置虚拟主机

850
2025/3/7 15:32:24
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在CentOS上设置Apache虚拟主机,你需要遵循以下步骤:

  1. 安装Apache Web服务器(如果尚未安装):
sudo yum install httpd
  1. 启动Apache服务并设置开机启动:
sudo systemctl start httpd
sudo systemctl enable httpd
  1. 创建一个新的目录,用于存放虚拟主机的网站文件。例如,创建一个名为/var/www/example.com的目录:
sudo mkdir /var/www/example.com
  1. 更改新创建的目录的所有权,以便Apache可以访问它:
sudo chown apache:apache /var/www/example.com
  1. 在新创建的目录中创建一个简单的HTML文件,例如index.html
echo "<h1>Welcome to Example.com!</h1>" | sudo tee /var/www/example.com/index.html
  1. 创建一个新的虚拟主机配置文件。在/etc/httpd/conf.d目录下创建一个名为example.com.conf的文件:
sudo vi /etc/httpd/conf.d/example.com.conf
  1. 在新创建的配置文件中添加以下内容,根据需要进行修改:
<VirtualHost *:80>
    ServerAdmin webmaster@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com

    <Directory /var/www/example.com>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /var/log/httpd/example.com-error.log
    CustomLog /var/log/httpd/example.com-access.log combined
</VirtualHost>
  1. 保存并关闭配置文件。

  2. 重启Apache服务以应用更改:

sudo systemctl restart httpd
  1. 确保你的防火墙允许HTTP和HTTPS流量:
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
  1. 更新你的DNS设置,将域名(例如example.com)指向服务器的IP地址。

现在,你应该可以通过访问http://example.com来查看你的虚拟主机网站。如果你想使用HTTPS,请确保已正确配置SSL证书,并在虚拟主机配置文件中添加相应的<VirtualHost *:443>配置。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: centos怎么给文件权限