温馨提示×

如何配置Apache虚拟主机在CentOS

小樊
43
2025-09-30 18:26:38
栏目: 云计算

在CentOS上配置Apache虚拟主机可以让你在同一台服务器上托管多个网站。以下是一个基本的步骤指南:

1. 安装Apache

首先,确保你已经安装了Apache。如果没有安装,可以使用以下命令进行安装:

sudo yum install httpd

2. 启动并启用Apache服务

安装完成后,启动Apache服务并设置开机自启:

sudo systemctl start httpd
sudo systemctl enable httpd

3. 创建虚拟主机配置文件

/etc/httpd/conf.d/目录下创建一个新的虚拟主机配置文件。例如,创建一个名为mywebsite.conf的文件:

sudo vi /etc/httpd/conf.d/mywebsite.conf

4. 配置虚拟主机

mywebsite.conf文件中添加以下内容:

<VirtualHost *:80>
    ServerAdmin webmaster@mywebsite.com
    DocumentRoot /var/www/mywebsite/html
    ServerName mywebsite.com
    ServerAlias www.mywebsite.com

    <Directory /var/www/mywebsite/html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /var/log/httpd/mywebsite-error.log
    CustomLog /var/log/httpd/mywebsite-access.log combined
</VirtualHost>
  • ServerAdmin: 管理员邮箱地址。
  • DocumentRoot: 网站的根目录。
  • ServerName: 主域名。
  • ServerAlias: 别名域名。
  • <Directory>: 指定网站根目录的访问权限。
  • ErrorLog: 错误日志文件路径。
  • CustomLog: 访问日志文件路径。

5. 创建网站根目录

创建网站根目录并设置适当的权限:

sudo mkdir -p /var/www/mywebsite/html
sudo chown -R apache:apache /var/www/mywebsite
sudo chmod -R 755 /var/www/mywebsite

6. 配置DNS

确保你的域名(例如mywebsite.com)指向你的服务器IP地址。你可以在你的DNS提供商的管理界面中进行配置。

7. 重启Apache服务

保存并关闭配置文件后,重启Apache服务以应用更改:

sudo systemctl restart httpd

8. 测试虚拟主机

打开浏览器并访问你的域名(例如http://mywebsite.com),你应该能够看到你的网站。

9. 配置SSL(可选)

如果你想为你的网站配置SSL,可以使用Let’s Encrypt免费证书。以下是基本步骤:

  1. 安装Certbot:

    sudo yum install certbot python2-certbot-apache
    
  2. 获取并安装证书:

    sudo certbot --apache -d mywebsite.com -d www.mywebsite.com
    
  3. 按照提示完成证书的安装和配置。

通过以上步骤,你应该能够在CentOS上成功配置Apache虚拟主机。

0