温馨提示×

CentOS如何编译安装Apache

小樊
36
2026-08-18 21:24:00
栏目: 智能运维

CentOS 上编译安装 Apache HTTP Server(httpd),一般步骤如下(以 CentOS 7 / 8 为例,适用于大多数情况)。


一、准备编译环境

1. 安装编译所需工具

yum groupinstall -y "Development Tools"
yum install -y gcc make autoconf automake

2. 安装依赖库

Apache 依赖以下库(常见):

yum install -y \
  pcre pcre-devel \
  zlib zlib-devel \
  openssl openssl-devel \
  expat expat-devel

二、下载 Apache 源码

1. 创建源码目录

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

2. 下载 Apache(以 2.4.x 为例)

wget https://downloads.apache.org/httpd/httpd-2.4.58.tar.gz
tar -zxvf httpd-2.4.58.tar.gz
cd httpd-2.4.58

可到官网查看最新版本:https://httpd.apache.org/download.cgi


三、依赖:APR 和 APR-Util(重要)

Apache 2.4 需要 APRAPR-Util

1. 下载 APR

cd /usr/local/src
wget https://downloads.apache.org/apr/apr-1.7.4.tar.gz
tar -zxvf apr-1.7.4.tar.gz

2. 下载 APR-Util

wget https://downloads.apache.org/apr/apr-util-1.6.3.tar.gz
tar -zxvf apr-util-1.6.3.tar.gz

3. 将 APR 放入 Apache 源码目录

cp -r apr-1.7.4 httpd-2.4.58/srclib/apr
cp -r apr-util-1.6.3 httpd-2.4.58/srclib/apr-util

四、编译安装 Apache

1. 进入 Apache 源码目录

cd /usr/local/src/httpd-2.4.58

2. 配置编译参数

推荐配置:

./configure \
--prefix=/usr/local/apache \
--sysconfdir=/etc/httpd \
--enable-so \
--enable-ssl \
--enable-rewrite \
--with-included-apr \
--with-mpm=prefork \
--enable-modules=most \
--enable-mods-shared=most

说明:

  • --prefix:安装路径
  • --enable-so:启用动态模块
  • --enable-ssl:HTTPS 支持
  • --enable-rewrite:URL 重写
  • --with-included-apr:使用自带 APR

3. 编译并安装

make
make install

五、启动 Apache

1. 启动 Apache

/usr/local/apache/bin/apachectl start

2. 测试

浏览器访问:

http://服务器IP

看到 It works! 表示成功。


六、配置环境变量(可选)

echo 'export PATH=/usr/local/apache/bin:$PATH' >> /etc/profile
source /etc/profile

七、注册为系统服务(CentOS 7/8)

1. 创建 systemd 服务文件

vi /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

[Install]
WantedBy=multi-user.target

2. 启动并设置开机自启

systemctl daemon-reload
systemctl start httpd
systemctl enable httpd

八、常见问题

1. 端口被占用

netstat -tunlp | grep 80

关闭占用端口的服务(如 nginx)。

2. 防火墙放行 80 端口

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

九、总结

✅ 编译安装 Apache 的核心步骤:

  1. 安装编译环境和依赖
  2. 下载 Apache + APR
  3. ./configure → make → make install
  4. 启动并配置服务

如果你需要 指定 PHP / 多版本 Apache / 性能优化 / 与 Nginx 搭配,可以继续问我。

0