温馨提示×

centos装apache要注意什么

小樊
35
2026-09-02 22:29:20
栏目: 智能运维

CentOS 上安装 Apache(httpd) 时,有几个常见但容易踩坑的点。下面按“必看 → 常见坑 → 推荐做法”给你梳理一下。


一、安装前要注意

1️⃣ 确认系统版本

不同 CentOS 版本命令略有区别:

cat /etc/centos-release
  • CentOS 7:使用 yum
  • CentOS 8 / Stream:使用 dnf(兼容 yum)

2️⃣ 关闭或配置防火墙

Apache 默认端口是 80 / 443

# 查看防火墙状态
systemctl status firewalld

# 开放端口
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

如果是云服务器,还要在 安全组 放行 80/443。


3️⃣ SELinux(最容易出问题)

CentOS 默认开启 SELinux,常常导致:

  • 网站目录 403
  • 无法写日志
  • 无法访问自定义目录

查看状态:

getenforce

常见解决方案:

✅ 推荐(安全):

setsebool -P httpd_can_network_connect on
chcon -R -t httpd_sys_content_t /var/www/html

❌ 不推荐(仅测试):

setenforce 0

二、安装 Apache

CentOS 7

yum install httpd -y
systemctl start httpd
systemctl enable httpd

CentOS 8 / Stream

dnf install httpd -y
systemctl start httpd
systemctl enable httpd

三、目录与权限要点

默认目录

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

权限注意

Apache 默认用户是 apache

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

四、虚拟主机(推荐做法)

/etc/httpd/conf.d/ 下新建:

<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /var/www/example
    <Directory /var/www/example>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

然后:

systemctl restart httpd

五、常见错误 & 排查

❌ 403 Forbidden

原因通常是:

  • SELinux
  • 目录权限不对
  • <Directory> 没配置 Require all granted

❌ 无法访问

检查:

systemctl status httpd
netstat -tunlp | grep :80
journalctl -xe

六、进阶建议(生产环境)

✅ 启用 HTTPS(Let’s Encrypt)

dnf install certbot python3-certbot-apache
certbot --apache

✅ 隐藏版本信息

ServerTokens Prod
ServerSignature Off

✅ 禁用目录浏览

Options -Indexes

总结一句话

CentOS 装 Apache,最关键是:防火墙 + SELinux + 权限

如果你告诉我:

  • CentOS 几?
  • 用于学习还是生产?
  • 是否用 PHP / 反向代理?

我可以给你一套更精准的配置方案

0