温馨提示×

Apache如何设置CentOS虚拟主机

小樊
52
2026-08-18 21:38:56
栏目: 云计算

CentOS 上配置 Apache 虚拟主机(Virtual Host),通常用于在一台服务器上运行多个网站。下面以 CentOS 7/8 + Apache(httpd) 为例,给你一个完整、常用、可操作的配置流程。


一、前提条件

1. 安装 Apache

# CentOS 7
yum install httpd -y

# CentOS 8 / Stream
dnf install httpd -y

2. 启动并设置开机自启

systemctl start httpd
systemctl enable httpd

3. 防火墙放行 HTTP/HTTPS

firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

二、虚拟主机目录结构(推荐)

示例:

/var/www/
├── site1
│   └── index.html
├── site2
│   └── index.html

创建目录:

mkdir -p /var/www/site1
mkdir -p /var/www/site2

创建测试页面:

echo "site1" > /var/www/site1/index.html
echo "site2" > /var/www/site2/index.html

三、配置虚拟主机

方式一(推荐):单独配置文件

在:

/etc/httpd/conf.d/

创建配置文件:

1️⃣ site1 虚拟主机

vim /etc/httpd/conf.d/site1.conf

内容:

<VirtualHost *:80>
    ServerName www.site1.com
    DocumentRoot /var/www/site1

    <Directory /var/www/site1>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /var/log/httpd/site1_error.log
    CustomLog /var/log/httpd/site1_access.log combined
</VirtualHost>

2️⃣ site2 虚拟主机

vim /etc/httpd/conf.d/site2.conf
<VirtualHost *:80>
    ServerName www.site2.com
    DocumentRoot /var/www/site2

    <Directory /var/www/site2>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /var/log/httpd/site2_error.log
    CustomLog /var/log/httpd/site2_access.log combined
</VirtualHost>

四、检查并重启 Apache

1. 检查配置

httpd -t

2. 重启 Apache

systemctl restart httpd

五、本地测试(无真实域名)

修改 hosts 文件(Windows / Linux / macOS)

192.168.1.100 www.site1.com
192.168.1.100 www.site2.com

浏览器访问:

http://www.site1.com
http://www.site2.com

六、常见问题

✅ 403 Forbidden

原因:

  • 目录权限不足
  • SELinux 未允许

解决方法:

chown -R apache:apache /var/www/site1
chown -R apache:apache /var/www/site2

SELinux(常见坑):

setsebool -P httpd_read_user_content 1

或暂时关闭测试:

setenforce 0

七、HTTPS 虚拟主机(简要)

如启用 HTTPS:

<VirtualHost *:443>
    ServerName www.site1.com
    DocumentRoot /var/www/site1

    SSLEngine on
    SSLCertificateFile /path/to/cert.crt
    SSLCertificateKeyFile /path/to/key.key
</VirtualHost>

八、总结(最简化流程)

1. 安装 httpd
2. 创建网站目录
3. 在 /etc/httpd/conf.d/ 写 *.conf
4. httpd -t → systemctl restart httpd
5. 测试访问

如果你需要:

  • CentOS 8 + Apache + PHP
  • 基于 IP 的虚拟主机
  • Laravel / WordPress 虚拟主机
  • Apache + HTTPS(Let’s Encrypt)

可以直接告诉我,我可以给你一步一步实战配置

0