在 CentOS 系统中配置 Apache2 虚拟主机,可以按照以下步骤进行:
首先,确保你已经安装了 Apache。如果没有安装,可以使用以下命令进行安装:
sudo yum install httpd
安装完成后,启动 Apache 服务并设置开机自启动:
sudo systemctl start httpd
sudo systemctl enable httpd
在 /etc/httpd/conf.d/ 目录下创建一个新的虚拟主机配置文件,例如 mydomain.conf:
sudo vi /etc/httpd/conf.d/mydomain.conf
在 mydomain.conf 文件中添加以下内容:
<VirtualHost *:80>
ServerAdmin webmaster@mydomain.com
DocumentRoot /var/www/mydomain/html
ServerName mydomain.com
ServerAlias www.mydomain.com
ErrorLog /var/log/httpd/mydomain-error.log
CustomLog /var/log/httpd/mydomain-access.log combined
</VirtualHost>
ServerAdmin:管理员邮箱地址。DocumentRoot:网站文件的根目录。ServerName:主域名。ServerAlias:别名域名。ErrorLog:错误日志文件路径。CustomLog:访问日志文件路径。根据 DocumentRoot 指定的路径创建网站文件目录,并添加一些示例文件:
sudo mkdir -p /var/www/mydomain/html
sudo echo "Welcome to My Domain" > /var/www/mydomain/html/index.html
确保你的域名已经指向了服务器的 IP 地址。你可以在你的域名注册商的管理面板中设置 DNS 记录。
配置完成后,重启 Apache 服务以使更改生效:
sudo systemctl restart httpd
打开浏览器,访问 http://mydomain.com,你应该能看到 “Welcome to My Domain” 的欢迎信息。
如果你希望为你的网站配置 SSL,可以使用 Let’s Encrypt 提供的免费 SSL 证书。以下是使用 Certbot 安装和配置 SSL 的步骤:
sudo yum install epel-release
sudo yum install certbot python2-certbot-apache
sudo certbot --apache -d mydomain.com -d www.mydomain.com
按照提示完成证书的安装和配置。
如果你启用了防火墙,确保开放 HTTP 和 HTTPS 端口:
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
通过以上步骤,你应该能够在 CentOS 系统上成功配置 Apache2 虚拟主机。