温馨提示×

怎么在CentOS配置Apache

小樊
47
2026-07-08 17:11:20
栏目: 智能运维

在 CentOS 上配置 Apache(httpd)一般分为 安装、启动、放行防火墙、配置虚拟主机 等几个步骤。下面以 CentOS 7 / 8 / Stream 为例说明(systemd 系统)。


一、安装 Apache(httpd)

1. 更新系统(可选但推荐)

sudo yum update -y

2. 安装 Apache

sudo yum install httpd -y

CentOS 中 Apache 的包名是 httpd


二、启动并设置开机自启

sudo systemctl start httpd
sudo systemctl enable httpd

检查状态:

sudo systemctl status httpd

看到 active (running) 表示成功。


三、放行防火墙(非常重要)

1. 查看防火墙状态

sudo firewall-cmd --state

2. 放行 HTTP / HTTPS

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

四、测试 Apache 是否成功

浏览器访问:

http://服务器IP

看到 Apache HTTP Server Test Page 即成功。


五、Apache 目录结构说明

目录 说明
/etc/httpd/ 主配置目录
/etc/httpd/conf/httpd.conf 主配置文件
/etc/httpd/conf.d/ 额外配置文件
/var/www/html/ 默认网站根目录
/var/log/httpd/ 日志目录

六、修改默认网站目录(可选)

1. 创建新目录

sudo mkdir -p /data/www
sudo chown -R apache:apache /data/www

2. 修改配置文件

编辑:

sudo vi /etc/httpd/conf/httpd.conf

找到:

DocumentRoot "/var/www/html"
<Directory "/var/www/html">

修改为:

DocumentRoot "/data/www"
<Directory "/data/www">
    AllowOverride All
    Require all granted
</Directory>

3. 重启 Apache

sudo systemctl restart httpd

七、配置虚拟主机(推荐)

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

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

示例:

<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /data/www/example

    <Directory /data/www/example>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /var/log/httpd/example_error.log
    CustomLog /var/log/httpd/example_access.log combined
</VirtualHost>

2. 创建目录

sudo mkdir -p /data/www/example
sudo chown -R apache:apache /data/www/example

3. 重启 Apache

sudo systemctl restart httpd

八、常见问题排查

1. 无法访问

  • 检查防火墙
  • 检查 SELinux
getenforce

临时关闭测试:

sudo setenforce 0

2. 查看错误日志

sudo tail -f /var/log/httpd/error_log

九、CentOS 8 / Stream 特别说明

如果使用 CentOS 8 / Stream,推荐使用:

sudo dnf install httpd -y

其余步骤相同。


如果你需要: ✅ 配置 HTTPS(SSL)
部署 PHP / Python / Java 项目
配置多站点
配合 Nginx 使用

可以告诉我你的具体需求,我可以一步步帮你配置。

0