温馨提示×

如何配置centos的apache

小樊
33
2026-09-15 01:43:53
栏目: 智能运维

下面按常见场景给你一份 CentOS 上配置 Apache(httpd)的实用指南,适用于 CentOS 7 / 8 / Stream(部分命令略有差异我会标注)。


一、安装 Apache

CentOS 7

yum install httpd -y

CentOS 8 / Stream

dnf install httpd -y

二、启动并设置开机自启

systemctl start httpd
systemctl enable httpd

查看状态:

systemctl status httpd

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

开放 80 端口(HTTP)

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

如需 HTTPS(443)

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

四、测试 Apache 是否正常工作

浏览器访问:

http://服务器IP

看到 Testing 123… 页面即成功。


五、网站目录结构

默认根目录

/var/www/html

写个测试页:

echo "Hello Apache" > /var/www/html/index.html

六、配置虚拟主机(多网站)

示例:配置 example.com

  1. 创建网站目录
mkdir -p /var/www/example.com
echo "example.com" > /var/www/example.com/index.html
  1. 创建配置文件
vi /etc/httpd/conf.d/example.conf

内容示例:

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/example.com
    <Directory /var/www/example.com>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
  1. 重启 Apache
systemctl restart httpd

七、启用 .htaccess(常见需求)

在虚拟主机或全局配置中:

AllowOverride All

八、常用配置文件位置

文件 说明
/etc/httpd/conf/httpd.conf 主配置文件
/etc/httpd/conf.d/ 额外配置
/var/log/httpd/ 日志目录

九、SELinux 注意事项(很多人踩坑)

如果页面打不开但配置没问题:

setsebool -P httpd_can_network_connect 1

或修改目录安全上下文:

semanage fcontext -a -t httpd_sys_content_t "/var/www/example.com(/.*)?"
restorecon -Rv /var/www/example.com

十、常见排错

# 查看错误日志
tail -f /var/log/httpd/error_log

# 检查配置语法
httpd -t

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

  • CentOS 具体版本
  • 是否要 HTTPS / PHP / 反向代理
  • 本地测试还是生产服务器

我可以给你更针对性的配置示例。

0