温馨提示×

centos如何设置apache虚拟主机

小樊
47
2026-09-06 02:34:31
栏目: 云计算

在 CentOS 上配置 Apache 虚拟主机(Virtual Host) 一般分为以下几个步骤(以 CentOS 7/8 + Apache 2.4 为例):


一、安装 Apache

# CentOS 7
yum install httpd -y

# CentOS 8
dnf install httpd -y

启动并设置开机自启:

systemctl start httpd
systemctl enable httpd

二、关闭或配置 SELinux(可选但常见)

# 临时关闭
setenforce 0

# 永久关闭(不推荐生产)
vi /etc/selinux/config
# 改为 SELINUX=disabled

或正确设置网站目录上下文:

semanage fcontext -a -t httpd_sys_content_t "/var/www/example.com(/.*)?"
restorecon -Rv /var/www/example.com

三、创建网站目录

mkdir -p /var/www/example.com/public_html

创建测试页面:

echo "Welcome to example.com" > /var/www/example.com/public_html/index.html

设置权限:

chown -R apache:apache /var/www/example.com
chmod -R 755 /var/www

四、创建虚拟主机配置文件

CentOS 中推荐放在:

/etc/httpd/conf.d/

创建配置文件:

vi /etc/httpd/conf.d/example.com.conf

示例配置(基于域名):

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html

    <Directory /var/www/example.com/public_html>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /var/log/httpd/example.com-error.log
    CustomLog /var/log/httpd/example.com-access.log combined
</VirtualHost>

五、检查配置并重启 Apache

httpd -t
systemctl restart httpd

六、本地测试(无 DNS 时)

修改本地 hosts 文件(Windows / Linux / macOS):

192.168.1.100 example.com

浏览器访问:

http://example.com

七、基于端口的虚拟主机(可选)

  1. 修改监听端口:
vi /etc/httpd/conf/httpd.conf
Listen 8080
  1. 虚拟主机配置:
<VirtualHost *:8080>
    DocumentRoot /var/www/port8080
    ServerName localhost
</VirtualHost>

八、常见问题

✅ 403 Forbidden

  • 目录权限不足
  • SELinux 未配置

✅ 无法访问

  • 防火墙未放行 80 端口
firewall-cmd --permanent --add-service=http
firewall-cmd --reload

如果你需要 HTTPS(Let’s Encrypt)多域名共用 IPApache + PHP 的示例,也可以告诉我。

0