温馨提示×

怎样用centos配apache

小樊
35
2026-09-18 02:53:18
栏目: 智能运维

下面给你一份**在 CentOS 上配置 Apache(httpd)**的实用步骤,适用于 CentOS 7 / 8 / Stream


一、安装 Apache

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

三、防火墙放行 Web 端口

开放 80 端口(HTTP)

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

如需 HTTPS(443):

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

四、测试 Apache 是否正常运行

浏览器访问:

http://服务器IP

看到 Apache 测试页 即成功。


五、网站目录与配置

默认网站根目录

/var/www/html

创建测试页面:

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

六、配置虚拟主机(可选)

示例:配置 example.com

  1. 创建网站目录
sudo mkdir -p /var/www/example.com/html
sudo chown -R apache:apache /var/www/example.com
  1. 创建配置文件
sudo vi /etc/httpd/conf.d/example.com.conf

内容示例:

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

七、常见命令

# 重启
sudo systemctl restart httpd

# 重载配置
sudo systemctl reload httpd

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

八、常见问题

SELinux 导致无法访问

sudo setsebool -P httpd_can_network_connect 1

或修改文件上下文:

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

如果你需要:

  • ✅ 配置 HTTPS(Let’s Encrypt)
  • ✅ 搭配 PHP / MySQL
  • ✅ 做 反向代理
  • ✅ 用 CentOS 9 / Rocky / Alma

告诉我你的具体需求即可。

0