温馨提示×

centos apache配置怎么弄

小樊
40
2026-08-29 23:40:50
栏目: 智能运维

下面给你一个CentOS 下配置 Apache(httpd)的常用完整流程,从安装到常见配置,基本照着做就能跑起来。


一、安装 Apache(httpd)

CentOS 7 / 8 通用:

# CentOS 7
yum install -y httpd

# CentOS 8+/Stream
dnf install -y httpd

查看版本:

httpd -v

二、启动并设置开机自启

systemctl start httpd
systemctl enable httpd

查看状态:

systemctl status httpd

三、防火墙放行 80 / 443 端口

firewalld(CentOS 默认)

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

SELinux(如果打不开页面)

查看状态:

getenforce

临时关闭(测试用):

setenforce 0

永久关闭(不推荐):

vi /etc/selinux/config
SELINUX=disabled

或者放行 httpd:

setsebool -P httpd_can_network_connect 1

四、默认站点目录

网站根目录:/var/www/html
配置文件:/etc/httpd/conf/httpd.conf

测试页面:

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

浏览器访问服务器 IP:

http://服务器IP

五、配置虚拟主机(多站点)

1️⃣ 创建网站目录

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

2️⃣ 新建虚拟主机配置

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>

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

3️⃣ 重启 Apache

systemctl restart httpd

六、URL 重写 / .htaccess 支持

确认配置中:

AllowOverride All

测试 .htaccess

vi /var/www/html/.htaccess
RewriteEngine On
RewriteRule ^test$ index.html

七、配置 HTTPS(Let’s Encrypt)

安装工具

yum install -y certbot python3-certbot-apache

申请证书

certbot --apache -d example.com -d www.example.com

证书自动续期:

certbot renew --dry-run

八、常用 Apache 命令

httpd -t          # 检查配置语法
systemctl restart httpd
systemctl reload httpd
apachectl status

九、常见坑点

✅ 403 Forbidden

  • 目录权限
  • SELinux
  • Require all granted

✅ 页面打不开

  • 防火墙
  • 80 端口未监听
  • 配置未 reload

✅ 多站点冲突

  • 确保 ServerName 唯一
  • 放在 /etc/httpd/conf.d/

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

  • ✅ CentOS 具体版本(7 / 8 / Stream)
  • ✅ 是 单站点 / 多站点 / HTTPS / PHP / 反向代理
  • ✅ 本机还是云服务器

我可以直接给你定制配置示例

0