在 CentOS 系统下,使用 Apache2(实际上在 CentOS 上称为 httpd)设置虚拟主机的步骤如下:
sudo yum install httpd
sudo systemctl start httpd
sudo systemctl enable httpd
mywebsite 的目录:sudo mkdir /var/www/mywebsite
sudo chown apache:apache /var/www/mywebsite
echo "<h1>Welcome to My Website</h1>" | sudo tee /var/www/mywebsite/index.html
mywebsite.conf 的文件:sudo vim /etc/httpd/conf.d/mywebsite.conf
<VirtualHost *:80>
ServerAdmin webmaster@mywebsite.com
ServerName mywebsite.com
ServerAlias www.mywebsite.com
DocumentRoot /var/www/mywebsite
ErrorLog /var/log/httpd/mywebsite-error.log
CustomLog /var/log/httpd/mywebsite-access.log combined
</VirtualHost>
保存并关闭配置文件。
检查 Apache 配置文件的语法是否正确:
sudo apachectl configtest
如果输出显示 “Syntax OK”,则表示配置正确。
sudo systemctl reload httpd
mywebsite.com 解析到服务器的 IP 地址。在 /etc/hosts 文件中添加以下行:127.0.0.1 mywebsite.com www.mywebsite.com
http://mywebsite.com,您应该看到 “Welcome to My Website” 页面。现在,您已成功在 CentOS 系统下为 Apache2 设置了虚拟主机。如果您有多个虚拟主机,只需为每个虚拟主机创建一个类似的配置文件,并确保为每个虚拟主机指定唯一的 ServerName 和 DocumentRoot。