在 CentOS 上安装 Apache(httpd,而不是 Ubuntu 里的 apache2) 时,有一些常见但容易踩坑的点。下面按「准备 → 安装 → 配置 → 安全 → 排错」给你梳理一下。
# CentOS 安装
yum install httpd # CentOS 7
dnf install httpd # CentOS 8 / Stream
cat /etc/redhat-release
不同版本命令略有区别(yum / dnf)。
否则外网访问不了:
# 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
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(生产环境)
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
原因通常是:
Require all grantedss -tunlp | grep :80
mod_ssl 使用 HTTPSOptions -IndexesServerTokens Prod
ServerSignature Off
如果你愿意,可以告诉我:
我可以给你一份可直接用的配置模板。