Apache 基础安装与配置
Basic Installation and Configuration
概述
Apache HTTP Server是世界上最广泛使用的Web服务器软件,支持多种操作系统和硬件平台。本文详细介绍Apache的安装方法、基础配置和初始化设置,为后续的高级配置奠定基础。
1. 系统要求与准备
1.1 硬件要求
最低配置:
- CPU: 1核心
- 内存: 512MB
- 磁盘: 1GB可用空间
推荐配置:
- CPU: 2核心或以上
- 内存: 2GB或以上
- 磁盘: 10GB可用空间
生产环境:
- CPU: 4核心或以上
- 内存: 8GB或以上
- 磁盘: 50GB可用空间(含日志)
1.2 软件依赖
# 必需依赖
- 操作系统: Linux (Ubuntu/CentOS/RHEL) 或 Windows
- 编译工具: gcc, make (源码安装需要)
- 库文件: PCRE, zlib, OpenSSL (可选)
# 可选依赖
- APR (Apache Portable Runtime)
- APR-util
- mod_ssl (SSL/TLS支持)
2. Ubuntu/Debian 安装
2.1 包管理器安装
#!/bin/bash
# install-apache-ubuntu.sh
# 更新包列表
sudo apt update
# 安装Apache
sudo apt install apache2 -y
# 安装常用模块
sudo apt install apache2-utils -y
# 启动并设置开机自启
sudo systemctl start apache2
sudo systemctl enable apache2
# 验证安装
apache2 -v
systemctl status apache2
echo "Apache安装完成!"
echo "默认网站目录: /var/www/html"
echo "配置文件目录: /etc/apache2"
echo "日志文件目录: /var/log/apache2"
2.2 防火墙配置
# Ubuntu UFW防火墙配置
sudo ufw allow 'Apache Full'
sudo ufw allow 'Apache'
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# 查看防火墙状态
sudo ufw status
2.3 基础目录结构
# Ubuntu Apache目录结构
/etc/apache2/
├── apache2.conf # 主配置文件
├── ports.conf # 端口配置
├── sites-available/ # 可用站点配置
│ ├── 000-default.conf
│ └── default-ssl.conf
├── sites-enabled/ # 启用站点配置
├── mods-available/ # 可用模块
├── mods-enabled/ # 启用模块
├── conf-available/ # 可用配置文件
└── conf-enabled/ # 启用配置文件
3. CentOS/RHEL 安装
3.1 YUM包管理器安装
#!/bin/bash
# install-apache-centos.sh
# CentOS 7/8 安装脚本
# 检查系统版本
if [ -f /etc/redhat-release ]; then
VERSION=$(cat /etc/redhat-release | grep -oE '[0-9]+' | head -1)
echo "检测到 CentOS/RHEL $VERSION"
else
echo "不支持的系统"
exit 1
fi
# 安装Apache (httpd)
if [ "$VERSION" = "7" ]; then
sudo yum update -y
sudo yum install httpd httpd-tools -y
elif [ "$VERSION" = "8" ]; then
sudo dnf update -y
sudo dnf install httpd httpd-tools -y
fi
# 启动并设置开机自启
sudo systemctl start httpd
sudo systemctl enable httpd
# 配置防火墙
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
# 验证安装
httpd -v
systemctl status httpd
echo "Apache安装完成!"
echo "默认网站目录: /var/www/html"
echo "配置文件: /etc/httpd/conf/httpd.conf"
echo "日志文件目录: /var/log/httpd"
3.2 CentOS目录结构
# CentOS Apache目录结构
/etc/httpd/
├── conf/
│ ├── httpd.conf # 主配置文件
│ └── magic
├── conf.d/ # 额外配置文件
│ ├── ssl.conf
│ └── welcome.conf
├── conf.modules.d/ # 模块配置
├── logs -> /var/log/httpd # 日志目录软链接
└── modules -> /usr/lib64/httpd/modules # 模块目录软链接
4. 源码编译安装
4.1 下载和编译
#!/bin/bash
# compile-apache-from-source.sh
# 设置版本和目录
APACHE_VERSION="2.4.57"
INSTALL_DIR="/opt/apache2"
SRC_DIR="/usr/local/src"
# 创建用户
sudo useradd -r -s /bin/false apache
# 安装编译依赖
sudo apt update
sudo apt install build-essential libapr1-dev libaprutil1-dev libpcre3-dev libssl-dev -y
# 下载源码
cd $SRC_DIR
wget https://downloads.apache.org/httpd/httpd-${APACHE_VERSION}.tar.gz
tar -xzf httpd-${APACHE_VERSION}.tar.gz
cd httpd-${APACHE_VERSION}
# 配置编译选项
./configure \
--prefix=$INSTALL_DIR \
--enable-rewrite \
--enable-ssl \
--enable-proxy \
--enable-proxy-http \
--enable-proxy-balancer \
--enable-headers \
--enable-deflate \
--enable-expires \
--enable-status \
--enable-info \
--with-mpm=prefork \
--with-ssl \
--with-pcre
# 编译和安装
make -j$(nproc)
sudo make install
# 创建systemd服务文件
sudo tee /etc/systemd/system/apache2.service > /dev/null << 'EOF'
[Unit]
Description=The Apache HTTP Server
After=network.target
[Service]
Type=forking
ExecStart=/opt/apache2/bin/httpd -DFOREGROUND
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s
[Install]
WantedBy=multi-user.target
EOF
# 启动服务
sudo systemctl daemon-reload
sudo systemctl start apache2
sudo systemctl enable apache2
echo "Apache源码编译安装完成!"
echo "安装目录: $INSTALL_DIR"
echo "配置文件: $INSTALL_DIR/conf/httpd.conf"
5. 基础配置
5.1 主配置文件解析
# /etc/apache2/apache2.conf (Ubuntu) 或 /etc/httpd/conf/httpd.conf (CentOS)
# 服务器根目录
ServerRoot "/etc/apache2"
# PID文件位置
PidFile ${APACHE_PID_FILE}
# 超时设置
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
# 用户和组
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
# 主机名和端口
ServerName localhost:80
Listen 80
# 目录权限设置
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# 默认文档设置
<IfModule mod_dir.c>
DirectoryIndex index.html index.htm index.php
</IfModule>
# 访问文件限制
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
5.2 基础安全配置
# 安全配置建议
# 隐藏Apache版本信息
ServerTokens Prod
ServerSignature Off
# 禁用服务器状态信息
<Location "/server-status">
SetHandler server-status
Require local
</Location>
<Location "/server-info">
SetHandler server-info
Require local
</Location>
# 防止访问敏感文件
<Files ".htaccess">
Require all denied
</Files>
<Files ".htpasswd">
Require all denied
</Files>
# 限制请求大小
LimitRequestBody 10485760 # 10MB
# 设置安全头
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options SAMEORIGIN
Header always set X-XSS-Protection "1; mode=block"
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
6. 创建测试站点
6.1 默认站点配置
# /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName localhost
DocumentRoot /var/www/html
# 日志配置
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# 目录配置
<Directory /var/www/html>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# 错误页面
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
</VirtualHost>
6.2 创建测试页面
#!/bin/bash
# create-test-pages.sh
WEBROOT="/var/www/html"
# 创建主页
sudo tee $WEBROOT/index.html > /dev/null << 'EOF'
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Apache Test Page</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.container { max-width: 800px; margin: 0 auto; }
.success { color: #28a745; }
.info { background: #f8f9fa; padding: 20px; border-left: 4px solid #007bff; }
</style>
</head>
<body>
<div class="container">
<h1 class="success">🎉 Apache HTTP Server 运行成功!</h1>
<div class="info">
<h3>服务器信息</h3>
<p><strong>服务器软件:</strong> Apache HTTP Server</p>
<p><strong>文档根目录:</strong> /var/www/html</p>
<p><strong>配置文件:</strong> /etc/apache2/ (Ubuntu) 或 /etc/httpd/ (CentOS)</p>
<p><strong>访问时间:</strong> <span id="datetime"></span></p>
</div>
<h3>测试功能</h3>
<ul>
<li><a href="/test.php">PHP信息页面</a> (需要安装PHP)</li>
<li><a href="/server-status">服务器状态</a> (需要启用mod_status)</li>
<li><a href="/server-info">服务器信息</a> (需要启用mod_info)</li>
</ul>
</div>
<script>
document.getElementById('datetime').textContent = new Date().toLocaleString();
</script>
</body>
</html>
EOF
# 创建PHP测试页面
sudo tee $WEBROOT/test.php > /dev/null << 'EOF'
<?php
echo "<h1>PHP 配置信息</h1>";
phpinfo();
?>
EOF
# 创建404错误页面
sudo tee $WEBROOT/404.html > /dev/null << 'EOF'
<!DOCTYPE html>
<html>
<head>
<title>页面未找到 - 404</title>
<style>body{font-family:Arial,sans-serif;text-align:center;margin-top:100px;}</style>
</head>
<body>
<h1>404 - 页面未找到</h1>
<p>抱歉,您访问的页面不存在。</p>
<a href="/">返回首页</a>
</body>
</html>
EOF
# 设置权限
sudo chown -R www-data:www-data $WEBROOT # Ubuntu
# sudo chown -R apache:apache $WEBROOT # CentOS
echo "测试页面创建完成!"
7. 常用管理命令
7.1 服务管理
# Ubuntu/Debian 系统
sudo systemctl start apache2 # 启动
sudo systemctl stop apache2 # 停止
sudo systemctl restart apache2 # 重启
sudo systemctl reload apache2 # 重新加载配置
sudo systemctl status apache2 # 查看状态
sudo systemctl enable apache2 # 开机自启
sudo systemctl disable apache2 # 禁用自启
# CentOS/RHEL 系统
sudo systemctl start httpd
sudo systemctl stop httpd
sudo systemctl restart httpd
sudo systemctl reload httpd
sudo systemctl status httpd
sudo systemctl enable httpd
sudo systemctl disable httpd
7.2 配置管理
# Ubuntu 站点管理
sudo a2ensite 000-default # 启用站点
sudo a2dissite 000-default # 禁用站点
# Ubuntu 模块管理
sudo a2enmod rewrite # 启用模块
sudo a2dismod rewrite # 禁用模块
# 配置测试
sudo apache2ctl configtest # Ubuntu
sudo httpd -t # CentOS
# 平滑重启
sudo apache2ctl graceful # Ubuntu
sudo httpd -k graceful # CentOS
# 查看已加载模块
apache2ctl -M # Ubuntu
httpd -M # CentOS
# 查看版本信息
apache2 -v # Ubuntu
httpd -v # CentOS
8. 初始化配置脚本
8.1 自动化配置脚本
#!/bin/bash
# apache-initial-setup.sh
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${GREEN}Apache HTTP Server 初始化配置脚本${NC}"
echo "================================================"
# 检测系统类型
if [ -f /etc/debian_version ]; then
SYSTEM="debian"
APACHE_SERVICE="apache2"
APACHE_CONFIG_DIR="/etc/apache2"
APACHE_LOG_DIR="/var/log/apache2"
elif [ -f /etc/redhat-release ]; then
SYSTEM="redhat"
APACHE_SERVICE="httpd"
APACHE_CONFIG_DIR="/etc/httpd"
APACHE_LOG_DIR="/var/log/httpd"
else
echo -e "${RED}不支持的操作系统${NC}"
exit 1
fi
echo -e "${YELLOW}检测到系统类型: $SYSTEM${NC}"
# 创建备份目录
BACKUP_DIR="/root/apache_backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p $BACKUP_DIR
# 备份原始配置
echo "备份原始配置文件..."
sudo cp -r $APACHE_CONFIG_DIR $BACKUP_DIR/
echo -e "${GREEN}配置文件已备份到: $BACKUP_DIR${NC}"
# 基础安全配置
configure_security() {
echo "配置基础安全设置..."
if [ "$SYSTEM" = "debian" ]; then
# Ubuntu配置
sudo tee -a $APACHE_CONFIG_DIR/apache2.conf > /dev/null << 'EOF'
# 安全配置
ServerTokens Prod
ServerSignature Off
# 安全头设置
<IfModule mod_headers.c>
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options SAMEORIGIN
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>
# 隐藏敏感文件
<FilesMatch "^\.">
Require all denied
</FilesMatch>
<FilesMatch "(^#.*#|\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
Require all denied
</FilesMatch>
EOF
else
# CentOS配置
sudo tee -a $APACHE_CONFIG_DIR/conf/httpd.conf > /dev/null << 'EOF'
# 安全配置
ServerTokens Prod
ServerSignature Off
# 安全头设置
LoadModule headers_module modules/mod_headers.so
<IfModule mod_headers.c>
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options SAMEORIGIN
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>
# 隐藏敏感文件
<FilesMatch "^\.">
Require all denied
</FilesMatch>
<FilesMatch "(^#.*#|\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
Require all denied
</FilesMatch>
EOF
fi
}
# 启用必要模块
enable_modules() {
echo "启用必要模块..."
if [ "$SYSTEM" = "debian" ]; then
sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod ssl
sudo a2enmod deflate
sudo a2enmod expires
else
# CentOS模块通常已经编译进去或者在配置中启用
echo "CentOS模块配置检查..."
fi
}
# 测试配置
test_configuration() {
echo "测试配置文件语法..."
if [ "$SYSTEM" = "debian" ]; then
if sudo apache2ctl configtest; then
echo -e "${GREEN}配置文件语法正确${NC}"
else
echo -e "${RED}配置文件语法错误${NC}"
return 1
fi
else
if sudo httpd -t; then
echo -e "${GREEN}配置文件语法正确${NC}"
else
echo -e "${RED}配置文件语法错误${NC}"
return 1
fi
fi
}
# 重启服务
restart_service() {
echo "重启Apache服务..."
if sudo systemctl restart $APACHE_SERVICE; then
echo -e "${GREEN}Apache服务重启成功${NC}"
else
echo -e "${RED}Apache服务重启失败${NC}"
return 1
fi
}
# 执行配置步骤
configure_security
enable_modules
if test_configuration; then
restart_service
echo -e "${GREEN}Apache初始化配置完成!${NC}"
echo "================================================"
echo "备份位置: $BACKUP_DIR"
echo "配置目录: $APACHE_CONFIG_DIR"
echo "日志目录: $APACHE_LOG_DIR"
echo "测试地址: http://localhost"
echo ""
echo "下一步建议:"
echo "1. 配置虚拟主机"
echo "2. 设置SSL证书"
echo "3. 配置防火墙规则"
echo "4. 设置日志轮转"
else
echo -e "${RED}配置失败,请检查错误信息${NC}"
exit 1
fi
9. 验证安装
9.1 功能验证脚本
#!/bin/bash
# verify-apache-installation.sh
echo "Apache HTTP Server 安装验证"
echo "=========================="
# 检查服务状态
check_service() {
if systemctl is-active apache2 >/dev/null 2>&1 || systemctl is-active httpd >/dev/null 2>&1; then
echo "✅ Apache服务正在运行"
return 0
else
echo "❌ Apache服务未运行"
return 1
fi
}
# 检查端口监听
check_ports() {
if netstat -tuln | grep :80 >/dev/null 2>&1; then
echo "✅ 端口80正在监听"
else
echo "❌ 端口80未监听"
fi
if netstat -tuln | grep :443 >/dev/null 2>&1; then
echo "✅ 端口443正在监听 (SSL)"
else
echo "⚠️ 端口443未监听 (SSL未配置)"
fi
}
# 检查HTTP响应
check_http_response() {
if curl -s -o /dev/null -w "%{http_code}" http://localhost | grep -q "200"; then
echo "✅ HTTP响应正常"
else
echo "❌ HTTP响应异常"
fi
}
# 检查配置文件
check_config() {
if [ -f "/etc/apache2/apache2.conf" ] || [ -f "/etc/httpd/conf/httpd.conf" ]; then
echo "✅ 配置文件存在"
else
echo "❌ 配置文件缺失"
fi
}
# 检查模块
check_modules() {
echo "已加载的关键模块:"
if command -v apache2ctl >/dev/null 2>&1; then
apache2ctl -M | grep -E "(rewrite|ssl|headers)" | head -5
elif command -v httpd >/dev/null 2>&1; then
httpd -M | grep -E "(rewrite|ssl|headers)" | head -5
fi
}
# 执行检查
check_service
check_ports
check_http_response
check_config
check_modules
echo ""
echo "验证完成!"
小结
通过本文学习,你应该掌握:
- Apache在不同操作系统上的安装方法
- 包管理器安装vs源码编译安装的优缺点
- Apache目录结构和配置文件组织
- 基础安全配置和优化设置
- 常用管理命令和故障排除方法
- 自动化安装和配置脚本的编写
下一篇文章将详细介绍Apache的架构和模块系统。