温馨提示×

centos下apache咋配置

小樊
46
2026-09-11 21:02:15
栏目: 智能运维

下面给你一份CentOS 下 Apache(httpd)常见配置指南,从安装到常用配置,适用于 CentOS 7 / 8 / Stream(Systemd 体系)。


一、安装 Apache

# CentOS 7/8
sudo yum install httpd -y
# 或 CentOS 8/Stream
sudo dnf install httpd -y

启动并设置开机自启:

sudo systemctl start httpd
sudo systemctl enable httpd

查看状态:

systemctl status httpd

二、防火墙放行(重要)

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

三、目录结构说明

/etc/httpd/
├── conf/httpd.conf        # 主配置文件
├── conf.d/                # 额外配置文件(推荐放虚拟主机)
├── logs/                  # 日志
/var/www/html/             # 默认网站根目录

四、基础配置(httpd.conf)

常见需要改的地方:

ServerName www.example.com:80
DocumentRoot "/var/www/html"

修改后重启:

sudo systemctl restart httpd

五、配置虚拟主机(推荐方式)

1. 创建网站目录

sudo mkdir -p /var/www/example.com/html
sudo chown -R apache:apache /var/www/example.com

2. 新建配置文件

sudo vi /etc/httpd/conf.d/example.conf

示例:

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

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

    ErrorLog /var/log/httpd/example_error.log
    CustomLog /var/log/httpd/example_access.log combined
</VirtualHost>

重启 Apache:

sudo systemctl restart httpd

六、启用 PHP(常见需求)

sudo yum install php php-cli php-common -y
sudo systemctl restart httpd

测试:

echo "<?php phpinfo(); ?>" > /var/www/html/info.php

浏览器访问:

http://服务器IP/info.php

七、启用 HTTPS(Let’s Encrypt)

sudo yum install certbot python3-certbot-apache -y
sudo certbot --apache

自动续期测试:

sudo certbot renew --dry-run

八、常见排错

1. 403 Forbidden

  • 目录权限不对
  • SELinux 未放行
sudo setsebool -P httpd_read_user_content 1
sudo chcon -R -t httpd_sys_content_t /var/www

2. 无法访问

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

九、常用命令总结

systemctl start httpd
systemctl stop httpd
systemctl restart httpd
systemctl status httpd
httpd -t   # 检查配置文件语法

如果你有具体需求(比如:多站点 / 反向代理 / 重定向 / 绑定域名 / 内网环境),可以直接说,我可以给你针对性配置示例

0