温馨提示×

centos下apache如何配

小樊
46
2026-09-06 02:15:29
栏目: 智能运维

下面按**“从零在 CentOS 上配置 Apache(httpd)”的思路,给你一份实用、可操作**的说明,涵盖安装、启动、目录、虚拟主机、防火墙、常见配置。


一、安装 Apache(CentOS 7/8/Stream 通用)

1. 安装

sudo yum install httpd -y

(CentOS 8 也可用 dnf install httpd -y

2. 启动并设置开机自启

sudo systemctl start httpd
sudo systemctl enable httpd

3. 查看状态

systemctl status httpd

二、防火墙放行 80 / 443

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

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


三、默认网站目录与配置文件

1. 网站根目录

/var/www/html

默认访问:

http://服务器IP

测试:

echo "hello apache" > /var/www/html/index.html

2. 主配置文件

/etc/httpd/conf/httpd.conf

常用参数:

DocumentRoot "/var/www/html"
Listen 80
ServerName localhost

修改后重载:

systemctl reload httpd

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

1. 创建网站目录

mkdir -p /var/www/example.com/public_html
echo "example.com" > /var/www/example.com/public_html/index.html

2. 创建虚拟主机配置

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

示例:

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

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

    ErrorLog /var/log/httpd/example.com-error.log
    CustomLog /var/log/httpd/example.com-access.log combined
</VirtualHost>

3. 检查并重载

httpd -t
systemctl reload httpd

五、开启 PHP(常见需求)

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

测试:

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

访问:

http://IP/info.php

六、开启 HTTPS(Let’s Encrypt)

1. 安装 certbot

yum install certbot python3-certbot-apache -y

2. 申请证书

certbot --apache -d example.com

自动配置 80 → 443 跳转。


七、常见排错

1. 403 Forbidden

  • 目录权限
chown -R apache:apache /var/www
chmod -R 755 /var/www
  • SELinux
setsebool -P httpd_read_user_content 1

2. 配置错误

httpd -t

八、你接下来可以告诉我

  • CentOS 几?(7 / 8 / Stream)
  • 单站点还是多站点?
  • 要不要 PHP / HTTPS?
  • 内网还是公网服务器?

我可以直接给你一套完整配置

0