温馨提示×

centos怎么编译安装apache

小樊
38
2026-08-30 00:57:53
栏目: 智能运维

下面以 CentOS 7/8 为例,介绍 源码编译安装 Apache HTTP Server(httpd) 的完整流程。
(以 Apache 2.4.x 为例,这是目前主流版本)


一、准备工作

1. 安装编译依赖

# CentOS 7
yum groupinstall -y "Development Tools"
yum install -y \
  gcc \
  make \
  autoconf \
  libtool \
  pcre-devel \
  openssl-devel \
  expat-devel \
  zlib-devel

# CentOS 8
dnf groupinstall -y "Development Tools"
dnf install -y \
  gcc \
  make \
  autoconf \
  libtool \
  pcre-devel \
  openssl-devel \
  expat-devel \
  zlib-devel

二、下载 Apache 源码及依赖

Apache 2.4 需要:

  • APR
  • APR-Util
  • httpd

1. 创建目录

mkdir -p /usr/local/src/apache
cd /usr/local/src/apache

2. 下载源码(推荐国内镜像)

wget https://dlcdn.apache.org//httpd/httpd-2.4.58.tar.gz

wget https://dlcdn.apache.org/apr/apr-1.7.4.tar.gz
wget https://dlcdn.apache.org/apr/apr-util-1.6.3.tar.gz

版本号可根据官网调整
https://httpd.apache.org/download.cgi


三、编译安装 APR 和 APR-Util

1. 安装 APR

tar -xf apr-1.7.4.tar.gz
cd apr-1.7.4
./configure --prefix=/usr/local/apr
make && make install
cd ..

2. 安装 APR-Util

tar -xf apr-util-1.6.3.tar.gz
cd apr-util-1.6.3
./configure \
  --prefix=/usr/local/apr-util \
  --with-apr=/usr/local/apr
make && make install
cd ..

四、编译安装 Apache(httpd)

1. 解压

tar -xf httpd-2.4.58.tar.gz
cd httpd-2.4.58

2. 配置编译参数

./configure \
  --prefix=/usr/local/apache \
  --sysconfdir=/etc/httpd \
  --enable-so \
  --enable-ssl \
  --enable-rewrite \
  --with-apr=/usr/local/apr \
  --with-apr-util=/usr/local/apr-util \
  --with-ssl \
  --with-pcre

常用模块说明:

  • --enable-so:启用动态模块
  • --enable-ssl:支持 HTTPS
  • --enable-rewrite:支持 URL 重写

3. 编译并安装

make
make install

安装完成后:

  • Apache 主目录:/usr/local/apache
  • 配置文件:/etc/httpd/httpd.conf

五、配置 Apache

1. 修改监听端口(可选)

vim /etc/httpd/httpd.conf

确认:

Listen 80
ServerName localhost:80

2. 启动 Apache

/usr/local/apache/bin/apachectl start

3. 验证

curl http://localhost

或浏览器访问服务器 IP。


六、设置系统服务(systemd)

1. 创建 service 文件

vim /etc/systemd/system/httpd.service

内容如下:

[Unit]
Description=Apache HTTP Server
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/apache/bin/apachectl start
ExecStop=/usr/local/apache/bin/apachectl stop
ExecReload=/usr/local/apache/bin/apachectl graceful
PIDFile=/usr/local/apache/logs/httpd.pid
PrivateTmp=true

[Install]
WantedBy=multi-user.target

2. 启用并启动

systemctl daemon-reload
systemctl enable httpd
systemctl start httpd
systemctl status httpd

七、防火墙放行 80 端口

firewalld

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

iptables(老系统)

iptables -I INPUT -p tcp --dport 80 -j ACCEPT
service iptables save

八、常见问题

1. configure 报错:APR not found

确认已正确安装 apr 和 apr-util,并指定路径。

2. 端口被占用

netstat -tunlp | grep 80

3. 403 Forbidden

检查:

  • DocumentRoot 权限
  • <Directory> 配置

九、总结

✅ 已成功在 CentOS 上 源码编译安装 Apache 2.4
✅ 支持 SSL、Rewrite
✅ 可接入 systemd 管理

如果你需要:

  • 编译 PHP + Apache
  • 开启 HTTPS(Let’s Encrypt)
  • 多站点配置(VirtualHost)

可以继续问我。

0