温馨提示×

centos装apache2要注意什么

小樊
36
2026-10-03 00:50:19
栏目: 智能运维

在 CentOS 上安装 Apache(httpd,而不是 Ubuntu 里的 apache2) 时,有一些常见但容易踩坑的点。下面按「准备 → 安装 → 配置 → 安全 → 排错」给你梳理一下。


一、CentOS 上 Apache 的名称

  • CentOS / RHEL 中 Apache 叫 httpd
  • Ubuntu / Debian 中才叫 apache2
# CentOS 安装
yum install httpd        # CentOS 7
dnf install httpd        # CentOS 8 / Stream

二、安装前后要注意的点

1️⃣ 确认系统版本

cat /etc/redhat-release

不同版本命令略有区别(yum / dnf)。


2️⃣ 防火墙必须放行 80 / 443

否则外网访问不了:

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

或(iptables):

iptables -I INPUT -p tcp --dport 80 -j ACCEPT

3️⃣ SELinux 是 CentOS 特有坑(非常重要)

SELinux 很可能 阻止 Apache 访问文件或端口。

查看状态:

getenforce

常见解决方案:

# 允许 httpd 访问网站目录
chcon -R -t httpd_sys_content_t /var/www/html

# 允许 httpd 监听非标准端口
semanage port -a -t http_port_t -p tcp 8080

⚠️ 不建议直接 setenforce 0 关闭 SELinux(生产环境)


4️⃣ 启动并设置开机自启

systemctl start httpd
systemctl enable httpd

检查状态:

systemctl status httpd

三、目录与权限问题

默认目录

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

权限建议

chown -R apache:apache /var/www/html
chmod -R 755 /var/www/html

四、虚拟主机配置注意

示例(CentOS):

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

    <Directory /var/www/html/example>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

然后:

systemctl restart httpd

五、常见排错

1️⃣ 403 Forbidden

原因通常是:

  • 目录没权限
  • SELinux 限制
  • Directory 配置少了 Require all granted

2️⃣ 无法访问

  • 防火墙
  • 云服务器安全组
  • httpd 没启动

3️⃣ 端口被占用

ss -tunlp | grep :80

六、生产环境建议

  • 开启 mod_ssl 使用 HTTPS
  • 关闭目录列表:Options -Indexes
  • 隐藏版本信息:
ServerTokens Prod
ServerSignature Off

如果你愿意,可以告诉我:

  • CentOS 几?
  • 是否云服务器?
  • 是否要 PHP / HTTPS / 多站点?

我可以给你一份可直接用的配置模板。

0 踩