温馨提示×

centos怎样配置apache2

小樊
45
2026-09-02 22:32:19
栏目: 智能运维

在 CentOS 上“Apache2”通常指的是 Apache HTTP Server(httpd)。下面是从安装到基本配置的完整步骤(以 CentOS 7/8/Stream 为例)。


一、安装 Apache(httpd)

1. 更新系统

sudo yum update -y

(CentOS 8 / Stream 可用 dnf)

2. 安装 Apache

sudo yum install httpd -y

二、启动并设置开机自启

sudo systemctl start httpd
sudo systemctl enable httpd

查看状态:

sudo systemctl status httpd

三、防火墙配置(非常重要)

开放 80 和 443 端口

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

四、测试 Apache 是否运行

浏览器访问:

http://服务器IP

看到 Apache Test Page 即成功。


五、Apache 目录结构(CentOS)

作用 路径
主配置文件 /etc/httpd/conf/httpd.conf
虚拟主机配置 /etc/httpd/conf.d/
网站根目录 /var/www/html
日志 /var/log/httpd/

六、配置虚拟主机(示例)

1. 创建网站目录

sudo mkdir -p /var/www/example.com/public_html
sudo chown -R apache:apache /var/www/example.com

2. 创建虚拟主机文件

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

内容示例:

<VirtualHost *:80>
    ServerName 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>

3. 重启 Apache

sudo systemctl restart httpd

七、启用 PHP(可选)

sudo yum install php php-cli php-common -y
sudo systemctl restart httpd

测试:

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

访问 http://IP/info.php


八、常见问题

1. 403 Forbidden

  • 检查 DocumentRoot 权限
  • 检查 SELinux
sudo setsebool -P httpd_read_user_content 1

2. 修改配置后不生效

sudo apachectl configtest
sudo systemctl restart httpd

如果你用的是 CentOS 9 / Rocky / AlmaLinux 或需要 HTTPS(Let’s Encrypt) 配置,也可以继续问我。

0 踩