Apache 配置基础 #
配置文件位置 #
不同系统的配置文件 #
text
┌─────────────────────────────────────────────────────────────┐
│ Apache 配置文件位置 │
├─────────────────────────────────────────────────────────────┤
│ │
│ Ubuntu/Debian: │
│ 主配置文件:/etc/apache2/apache2.conf │
│ 端口配置:/etc/apache2/ports.conf │
│ 站点配置:/etc/apache2/sites-available/ │
│ 模块配置:/etc/apache2/mods-available/ │
│ │
│ CentOS/RHEL: │
│ 主配置文件:/etc/httpd/conf/httpd.conf │
│ 额外配置:/etc/httpd/conf.d/ │
│ 模块配置:/etc/httpd/conf.modules.d/ │
│ │
│ macOS (Homebrew): │
│ 主配置文件:/opt/homebrew/etc/httpd/httpd.conf │
│ │
│ Windows: │
│ 主配置文件:C:\Apache24\conf\httpd.conf │
│ │
│ 源码编译: │
│ 主配置文件:/usr/local/apache2/conf/httpd.conf │
│ │
└─────────────────────────────────────────────────────────────┘
配置文件结构 #
Ubuntu/Debian 结构 #
text
/etc/apache2/
│
├── apache2.conf # 主配置文件
│ │
│ ├── 包含 ports.conf # 端口配置
│ │
│ ├── 包含 mods-enabled/ # 已启用模块
│ │ ├── *.load # 模块加载文件
│ │ └── *.conf # 模块配置文件
│ │
│ ├── 包含 conf-enabled/ # 已启用配置
│ │ └── *.conf # 额外配置文件
│ │
│ └── 包含 sites-enabled/ # 已启用站点
│ └── *.conf # 虚拟主机配置
│
├── sites-available/ # 可用站点配置
│ ├── 000-default.conf # 默认站点
│ └── default-ssl.conf # 默认 SSL 站点
│
├── mods-available/ # 可用模块
│ ├── rewrite.load
│ ├── ssl.load
│ └── ...
│
└── conf-available/ # 可用配置
├── charset.conf
├── security.conf
└── ...
主配置文件解析 #
apache
# ============================================
# Apache 主配置文件结构 (apache2.conf)
# ============================================
# 1. 全局环境配置
# 设置服务器运行环境
ServerRoot "/etc/apache2"
# 服务器根目录
Timeout 300
# 请求超时时间(秒)
KeepAlive On
# 保持连接开启
MaxKeepAliveRequests 100
# 每个连接最大请求数
KeepAliveTimeout 5
# 保持连接超时时间
# 2. MPM 配置
# 多处理模块配置(根据使用的 MPM 加载不同配置)
# Prefork MPM(默认)
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
# Worker MPM
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
# Event MPM
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
# 3. 用户和组
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
# 4. 日志配置
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
# 5. 包含其他配置文件
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
Include ports.conf
# 6. 目录访问控制
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
# 7. 文档根目录
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
# 8. 包含站点配置
IncludeOptional sites-enabled/*.conf
配置语法规则 #
基本语法 #
text
┌─────────────────────────────────────────────────────────────┐
│ Apache 配置语法 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. 指令格式 │
│ 指令名 参数 [参数...] │
│ │
│ 示例: │
│ ServerName example.com │
│ Listen 80 │
│ DocumentRoot /var/www/html │
│ │
│ 2. 指令块 │
│ <块类型 参数> │
│ 指令... │
│ </块类型> │
│ │
│ 示例: │
│ <Directory /var/www/html> │
│ Options Indexes │
│ AllowOverride All │
│ </Directory> │
│ │
│ 3. 注释 │
│ # 这是单行注释 │
│ │
│ 4. 路径写法 │
│ - 使用正斜杠 / (推荐) │
│ - Windows 下也可用反斜杠 \ │
│ - 路径可以用引号包围 │
│ │
└─────────────────────────────────────────────────────────────┘
常用指令块 #
apache
# ============================================
# 常用指令块类型
# ============================================
# 1. Directory - 目录配置
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# 2. Files - 文件配置
<Files ".ht*">
Require all denied
</Files>
# 3. Location - URL 路径配置
<Location /server-status>
SetHandler server-status
Require local
</Location>
# 4. VirtualHost - 虚拟主机
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example
</VirtualHost>
# 5. IfModule - 条件判断模块
<IfModule mod_ssl.c>
# SSL 相关配置
</IfModule>
# 6. IfDefine - 条件判断定义
<IfDefine DEBUG>
LogLevel debug
</IfDefine>
# 7. Limit - 限制 HTTP 方法
<Limit GET POST>
Require all granted
</Limit>
# 8. LimitExcept - 排除特定方法
<LimitExcept GET POST>
Require all denied
</LimitExcept>
核心指令详解 #
服务器标识指令 #
apache
# ============================================
# 服务器标识配置
# ============================================
# ServerName - 服务器主机名
ServerName www.example.com:80
# ServerAlias - 服务器别名(在虚拟主机中使用)
ServerAlias example.com
# ServerAdmin - 管理员邮箱
ServerAdmin webmaster@example.com
# ServerSignature - 错误页面底部签名
ServerSignature Off
# On: 显示服务器版本
# Off: 不显示
# EMail: 显示邮箱链接
# ServerTokens - 响应头中的服务器信息
ServerTokens Prod
# Full: Apache/2.4.52 (Unix) OpenSSL/1.1.1
# OS: Apache/2.4.52 (Unix)
# Minimal: Apache/2.4.52
# Minor: Apache/2.4
# Major: Apache/2
# Prod: Apache
网络配置指令 #
apache
# ============================================
# 网络配置
# ============================================
# Listen - 监听端口
Listen 80
Listen 443
Listen 192.168.1.100:8080 # 监听特定 IP
# Timeout - 请求超时
Timeout 300
# KeepAlive - 保持连接
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
# HostnameLookups - DNS 反向解析
HostnameLookups Off
# On: 记录主机名(影响性能)
# Off: 记录 IP 地址
# Double: 双重验证
文档根目录指令 #
apache
# ============================================
# 文档根目录配置
# ============================================
# DocumentRoot - 网站根目录
DocumentRoot /var/www/html
# DirectoryIndex - 默认首页
DirectoryIndex index.html index.php index.htm
# Options - 目录选项
# Indexes: 目录列表(无首页时)
# FollowSymLinks: 跟随符号链接
# SymLinksIfOwnerMatch: 仅当所有者匹配时跟随
# ExecCGI: 执行 CGI 脚本
# Includes: SSI 支持
# MultiViews: 内容协商
# All: 所有选项
# None: 无选项
<Directory /var/www/html>
Options -Indexes +FollowSymLinks
# - 前缀表示禁用
# + 前缀表示启用
</Directory>
# AllowOverride - .htaccess 覆盖权限
# All: 允许所有指令
# None: 不允许任何指令
# AuthConfig: 认证相关
# FileInfo: 文档类型相关
# Indexes: 索引相关
# Limit: 访问控制相关
AllowOverride All
AllowOverride None
AllowOverride AuthConfig FileInfo
访问控制指令 #
apache
# ============================================
# 访问控制(Apache 2.4 新语法)
# ============================================
# 允许所有访问
Require all granted
# 拒绝所有访问
Require all denied
# 允许特定 IP
Require ip 192.168.1.0/24
Require ip 10.0.0.0/8
# 允许特定主机
Require host example.com
# 允许本地访问
Require local
# 组合条件
<RequireAll>
Require all granted
Require not ip 192.168.1.100
</RequireAll>
<RequireAny>
Require ip 192.168.1.0/24
Require host trusted.example.com
</RequireAny>
# ============================================
# 旧语法(Apache 2.2,已弃用)
# ============================================
# Order allow,deny
# Allow from all
# Deny from 192.168.1.100
日志配置指令 #
apache
# ============================================
# 日志配置
# ============================================
# ErrorLog - 错误日志位置
ErrorLog ${APACHE_LOG_DIR}/error.log
# LogLevel - 日志级别
LogLevel warn
# emerg: 紧急情况
# alert: 必须立即处理
# crit: 严重情况
# error: 错误
# warn: 警告
# notice: 正常但重要
# info: 信息
# debug: 调试信息
# CustomLog - 访问日志
CustomLog ${APACHE_LOG_DIR}/access.log combined
# 日志格式定义
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
# 格式说明符:
# %h - 客户端 IP
# %l - 远程登录名(通常 -)
# %u - 认证用户名
# %t - 请求时间
# %r - 请求行
# %>s - 响应状态码
# %b - 响应大小(字节)
# %{Referer}i - Referer 头
# %{User-Agent}i - User-Agent 头
模块管理 #
Ubuntu/Debian 模块管理 #
bash
# 查看可用模块
ls /etc/apache2/mods-available/
# 查看已启用模块
ls /etc/apache2/mods-enabled/
# 启用模块
sudo a2enmod rewrite
sudo a2enmod ssl
sudo a2enmod headers
# 禁用模块
sudo a2dismod rewrite
sudo a2dismod ssl
# 启用后需要重启 Apache
sudo systemctl restart apache2
CentOS/RHEL 模块管理 #
bash
# 查看已加载模块
httpd -M
# 启用模块(编辑配置文件)
# 在 /etc/httpd/conf.modules.d/ 目录下
# 或在 httpd.conf 中取消注释 LoadModule 行
# 启用 rewrite 模块
echo "LoadModule rewrite_module modules/mod_rewrite.so" | \
sudo tee /etc/httpd/conf.modules.d/rewrite.conf
常用模块列表 #
text
┌─────────────────────────────────────────────────────────────┐
│ 常用 Apache 模块 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 核心模块: │
│ ├── core 核心功能 │
│ ├── mpm_prefork Prefork MPM │
│ ├── mpm_worker Worker MPM │
│ ├── mpm_event Event MPM │
│ └── so 动态模块加载 │
│ │
│ 功能模块: │
│ ├── authz_core 访问控制核心 │
│ ├── authn_core 认证核心 │
│ ├── rewrite URL 重写 │
│ ├── ssl SSL/TLS 支持 │
│ ├── proxy 代理模块 │
│ ├── headers HTTP 头操作 │
│ ├── deflate Gzip 压缩 │
│ ├── expires 缓存控制 │
│ └── cache 缓存功能 │
│ │
│ 语言模块: │
│ ├── php PHP 支持 │
│ ├── wsgi Python 支持 │
│ └── perl Perl 支持 │
│ │
└─────────────────────────────────────────────────────────────┘
.htaccess 文件 #
.htaccess 基础 #
text
┌─────────────────────────────────────────────────────────────┐
│ .htaccess 文件 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 特点: │
│ - 目录级别的配置文件 │
│ - 无需重启服务器即可生效 │
│ - 会覆盖上级目录的配置 │
│ - 适用于虚拟主机用户 │
│ │
│ 注意事项: │
│ - 需要 AllowOverride 开启 │
│ - 会影响性能(每次请求都读取) │
│ - 生产环境建议放在主配置文件 │
│ │
│ 位置: │
│ /var/www/html/.htaccess # 网站根目录 │
│ /var/www/html/admin/.htaccess # admin 目录 │
│ │
└─────────────────────────────────────────────────────────────┘
.htaccess 示例 #
apache
# ============================================
# .htaccess 常用配置示例
# ============================================
# 开启 URL 重写
RewriteEngine On
# 强制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# 自定义错误页面
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
# 禁止目录列表
Options -Indexes
# 设置默认首页
DirectoryIndex index.php index.html
# 访问控制
Order Allow,Deny
Allow from all
Deny from 192.168.1.100
# 密码保护
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
# 防盗链
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example.com/ [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,NC]
# 缓存控制
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
# Gzip 压缩
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
配置验证与调试 #
验证配置语法 #
bash
# 检查配置语法
sudo apache2ctl configtest # Ubuntu/Debian
sudo apachectl configtest # CentOS/RHEL
sudo httpd -t # 通用
# 详细检查
sudo apache2ctl -S # 显示虚拟主机配置
常见配置错误 #
text
┌─────────────────────────────────────────────────────────────┐
│ 常见配置错误 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. 语法错误 │
│ AH00526: Syntax error on line XX │
│ 原因:拼写错误、缺少引号、标签未闭合 │
│ 解决:检查配置文件语法 │
│ │
│ 2. 端口被占用 │
│ (98)Address already in use: AH00072 │
│ 原因:端口已被其他程序使用 │
│ 解决:停止占用程序或更换端口 │
│ │
│ 3. 权限问题 │
│ AH00035: access to / denied │
│ 原因:目录权限或 Require 配置错误 │
│ 解决:检查目录权限和访问控制配置 │
│ │
│ 4. 模块未加载 │
│ Invalid command 'RewriteEngine' │
│ 原因:模块未启用 │
│ 解决:a2enmod 启用对应模块 │
│ │
│ 5. DocumentRoot 不存在 │
│ AH00112: Warning: DocumentRoot does not exist │
│ 原因:指定的目录不存在 │
│ 解决:创建目录或修改路径 │
│ │
└─────────────────────────────────────────────────────────────┘
调试技巧 #
bash
# 查看完整配置
sudo apache2ctl -V # 显示编译参数
sudo apache2ctl -S # 显示虚拟主机设置
sudo apache2ctl -M # 显示已加载模块
# 查看错误日志
sudo tail -f /var/log/apache2/error.log
# 增加日志级别
# 在配置文件中设置
LogLevel debug
配置最佳实践 #
安全配置建议 #
apache
# ============================================
# 安全配置建议
# ============================================
# 隐藏服务器版本信息
ServerTokens Prod
ServerSignature Off
# 禁止访问隐藏文件
<FilesMatch "^\.">
Require all denied
</FilesMatch>
# 禁止访问备份文件
<FilesMatch "~$">
Require all denied
</FilesMatch>
# 限制请求体大小
LimitRequestBody 10485760
# 限制请求头数量
LimitRequestFields 50
# 限制请求行长度
LimitRequestLine 8190
# 禁用目录列表
Options -Indexes
# 禁用符号链接跟随(如果不需要)
Options -FollowSymLinks
性能配置建议 #
apache
# ============================================
# 性能配置建议
# ============================================
# 启用保持连接
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
# 根据服务器资源调整 MPM
<IfModule mpm_event_module>
ServerLimit 16
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 1000
</IfModule>
# 禁用 .htaccess(如果不需要)
AllowOverride None
# 启用压缩
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
# 启用缓存
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/* "access plus 1 year"
</IfModule>
下一步 #
了解了配置基础后,继续学习 基本命令,掌握 Apache 的启动、停止、重载等操作!
最后更新:2026-03-29